Skip to content

Commit

Permalink
Added tasks 477, 478, 479, 480.
Browse files Browse the repository at this point in the history
  • Loading branch information
ThanhNIT authored Jan 1, 2023
1 parent f953133 commit 0411163
Show file tree
Hide file tree
Showing 13 changed files with 486 additions and 142 deletions.
288 changes: 146 additions & 142 deletions README.md

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package g0401_0500.s0477_total_hamming_distance

// #Medium #Array #Math #Bit_Manipulation #2023_01_01_Time_298_ms_(100.00%)_Space_38.6_MB_(100.00%)

class Solution {
fun totalHammingDistance(nums: IntArray): Int {
var ans = 0
val n = nums.size
for (i in 0..31) {
var ones = 0
for (k in nums) {
ones += k shr i and 1
}
ans = ans + ones * (n - ones)
}
return ans
}
}
31 changes: 31 additions & 0 deletions src/main/kotlin/g0401_0500/s0477_total_hamming_distance/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
477\. Total Hamming Distance

Medium

The [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between two integers is the number of positions at which the corresponding bits are different.

Given an integer array `nums`, return _the sum of **Hamming distances** between all the pairs of the integers in_ `nums`.

**Example 1:**

**Input:** nums = [4,14,2]

**Output:** 6

**Explanation:** In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just showing the four bits relevant in this case).

The answer will be:

HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.

**Example 2:**

**Input:** nums = [4,14,4]

**Output:** 4

**Constraints:**

* <code>1 <= nums.length <= 10<sup>4</sup></code>
* <code>0 <= nums[i] <= 10<sup>9</sup></code>
* The answer for the given input will fit in a **32-bit** integer.
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package g0401_0500.s0478_generate_random_point_in_a_circle

// #Medium #Math #Geometry #Randomized #Rejection_Sampling
// #2023_01_01_Time_862_ms_(100.00%)_Space_70_MB_(66.67%)

import java.util.Random

@Suppress("kotlin:S2245")
class Solution(private val radius: Double, private val xCenter: Double, private val yCenter: Double) {
private val random: Random = Random()
fun randPoint(): DoubleArray {
var x = getCoordinate(xCenter)
var y = getCoordinate(yCenter)
while (getDistance(x, y) >= radius * radius) {
x = getCoordinate(xCenter)
y = getCoordinate(yCenter)
}
return doubleArrayOf(x, y)
}

private fun getDistance(x: Double, y: Double): Double {
return (xCenter - x) * (xCenter - x) + (yCenter - y) * (yCenter - y)
}

private fun getCoordinate(center: Double): Double {
return center - radius + random.nextDouble() * 2 * radius
}
}

/*
* Your Solution object will be instantiated and called as such:
* var obj = Solution(radius, x_center, y_center)
* var param_1 = obj.randPoint()
*/
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
478\. Generate Random Point in a Circle

Medium

Given the radius and the position of the center of a circle, implement the function `randPoint` which generates a uniform random point inside the circle.

Implement the `Solution` class:

* `Solution(double radius, double x_center, double y_center)` initializes the object with the radius of the circle `radius` and the position of the center `(x_center, y_center)`.
* `randPoint()` returns a random point inside the circle. A point on the circumference of the circle is considered to be in the circle. The answer is returned as an array `[x, y]`.

**Example 1:**

**Input** ["Solution", "randPoint", "randPoint", "randPoint"] [[1.0, 0.0, 0.0], [], [], []]

**Output:** [null, [-0.02493, -0.38077], [0.82314, 0.38945], [0.36572, 0.17248]]

**Explanation:**

Solution solution = new Solution(1.0, 0.0, 0.0);
solution.randPoint(); // return [-0.02493, -0.38077]
solution.randPoint(); // return [0.82314, 0.38945]
solution.randPoint(); // return [0.36572, 0.17248]

**Constraints:**

* <code>0 < radius <= 10<sup>8</sup></code>
* <code>-10<sup>7</sup> <= x_center, y_center <= 10<sup>7</sup></code>
* At most <code>3 * 10<sup>4</sup></code> calls will be made to `randPoint`.
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package g0401_0500.s0479_largest_palindrome_product

// #Hard #Math #2023_01_01_Time_147_ms_(100.00%)_Space_32.8_MB_(100.00%)

@Suppress("NAME_SHADOWING")
class Solution {
fun largestPalindrome(n: Int): Int {
val pow10 = Math.pow(10.0, n.toDouble()).toLong()
val max = (pow10 - 1) * (pow10 - Math.sqrt(pow10.toDouble()).toLong() + 1)
val left = max / pow10
var t = pow10 / 11
t -= t.inv() and 1L
for (i in left downTo 1) {
var j = t
val num = gen(i)
while (j >= i / 11) {
if (num % j == 0L) {
return (num % 1337).toInt()
}
j -= 2
}
}
return 9
}

private fun gen(x: Long): Long {
var x = x
var r = x
while (x > 0) {
r = r * 10 + x % 10
x /= 10
}
return r
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
479\. Largest Palindrome Product

Hard

Given an integer n, return _the **largest palindromic integer** that can be represented as the product of two `n`\-digits integers_. Since the answer can be very large, return it **modulo** `1337`.

**Example 1:**

**Input:** n = 2

**Output:** 987 Explanation: 99 x 91 = 9009, 9009 % 1337 = 987

**Example 2:**

**Input:** n = 1

**Output:** 9

**Constraints:**

* `1 <= n <= 8`
64 changes: 64 additions & 0 deletions src/main/kotlin/g0401_0500/s0480_sliding_window_median/Solution.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package g0401_0500.s0480_sliding_window_median

// #Hard #Array #Hash_Table #Heap_Priority_Queue #Sliding_Window
// #2023_01_01_Time_409_ms_(100.00%)_Space_44.6_MB_(81.48%)

import java.util.TreeSet

class Solution {
fun medianSlidingWindow(nums: IntArray, k: Int): DoubleArray {
require(k >= 1) { "Input is invalid" }
val len = nums.size
val result = DoubleArray(len - k + 1)
if (k == 1) {
for (i in 0 until len) {
result[i] = nums[i].toDouble()
}
return result
}
val comparator = Comparator { a: Int?, b: Int? ->
if (nums[a!!] != nums[b!!]
) Integer.compare(nums[a], nums[b]) else Integer.compare(a, b)
}
val smallNums = TreeSet(comparator.reversed())
val largeNums = TreeSet(comparator)
for (i in 0 until len) {
if (i >= k) {
removeElement(smallNums, largeNums, i - k)
}
addElement(smallNums, largeNums, i)
if (i >= k - 1) {
result[i - (k - 1)] = getMedian(smallNums, largeNums, nums)
}
}
return result
}

private fun addElement(smallNums: TreeSet<Int?>, largeNums: TreeSet<Int?>, idx: Int) {
smallNums.add(idx)
largeNums.add(smallNums.pollFirst()!!)
if (smallNums.size < largeNums.size) {
smallNums.add(largeNums.pollFirst())
}
}

private fun removeElement(smallNums: TreeSet<Int?>, largeNums: TreeSet<Int?>, idx: Int) {
if (largeNums.contains(idx)) {
largeNums.remove(idx)
if (smallNums.size == largeNums.size + 2) {
largeNums.add(smallNums.pollFirst()!!)
}
} else {
smallNums.remove(idx)
if (smallNums.size < largeNums.size) {
smallNums.add(largeNums.pollFirst())
}
}
}

private fun getMedian(smallNums: TreeSet<Int?>, largeNums: TreeSet<Int?>, nums: IntArray): Double {
return if (smallNums.size == largeNums.size) {
(nums[smallNums.first()!!].toDouble() + nums[largeNums.first()!!]) / 2
} else nums[smallNums.first()!!].toDouble()
}
}
31 changes: 31 additions & 0 deletions src/main/kotlin/g0401_0500/s0480_sliding_window_median/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
480\. Sliding Window Median

Hard

The **median** is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values.

* For examples, if <code>arr = [2,<ins>3</ins>,4]</code>, the median is `3`.
* For examples, if <code>arr = [1,<ins>2,3</ins>,4]</code>, the median is `(2 + 3) / 2 = 2.5`.

You are given an integer array `nums` and an integer `k`. There is a sliding window of size `k` which is moving from the very left of the array to the very right. You can only see the `k` numbers in the window. Each time the sliding window moves right by one position.

Return _the median array for each window in the original array_. Answers within <code>10<sup>-5</sup></code> of the actual value will be accepted.

**Example 1:**

**Input:** nums = [1,3,-1,-3,5,3,6,7], k = 3

**Output:** [1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000]

**Explanation:** Window position Median --------------- ----- [**1 3 -1**] -3 5 3 6 7 1 1 [**3 -1 -3**] 5 3 6 7 -1 1 3 [**\-1 -3 5**] 3 6 7 -1 1 3 -1 [**\-3 5 3**] 6 7 3 1 3 -1 -3 [**5 3 6**] 7 5 1 3 -1 -3 5 [**3 6 7**] 6

**Example 2:**

**Input:** nums = [1,2,3,4,2,3,1,4,2], k = 3

**Output:** [2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000]

**Constraints:**

* <code>1 <= k <= nums.length <= 10<sup>5</sup></code>
* <code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code>
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package g0401_0500.s0477_total_hamming_distance

import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.jupiter.api.Test

internal class SolutionTest {
@Test
fun totalHammingDistance() {
assertThat(Solution().totalHammingDistance(intArrayOf(4, 14, 2)), equalTo(6))
}

@Test
fun totalHammingDistance2() {
assertThat(Solution().totalHammingDistance(intArrayOf(4, 14, 4)), equalTo(4))
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package g0401_0500.s0478_generate_random_point_in_a_circle

import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.jupiter.api.Test

internal class SolutionTest {
@Test
fun randPoint() {
val solution = Solution(1.0, 0.0, 0.0)
solution.randPoint()
solution.randPoint()
solution.randPoint()
assertThat(solution, equalTo(solution))
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package g0401_0500.s0479_largest_palindrome_product

import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.jupiter.api.Test

internal class SolutionTest {
@Test
fun largestPalindrome() {
assertThat(Solution().largestPalindrome(2), equalTo(987))
}

@Test
fun largestPalindrome2() {
assertThat(Solution().largestPalindrome(1), equalTo(9))
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package g0401_0500.s0480_sliding_window_median

import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.jupiter.api.Test

internal class SolutionTest {
@Test
fun medianSlidingWindow() {
assertThat(
Solution().medianSlidingWindow(intArrayOf(1, 3, -1, -3, 5, 3, 6, 7), 3),
equalTo(doubleArrayOf(1.00000, -1.00000, -1.00000, 3.00000, 5.00000, 6.00000))
)
}

@Test
fun medianSlidingWindow2() {
assertThat(
Solution().medianSlidingWindow(intArrayOf(1, 2, 3, 4, 2, 3, 1, 4, 2), 3),
equalTo(
doubleArrayOf(
2.00000, 3.00000, 3.00000, 3.00000, 2.00000, 3.00000, 2.00000
)
)
)
}
}

0 comments on commit 0411163

Please sign in to comment.