-
Notifications
You must be signed in to change notification settings - Fork 93
Added tasks 374, 378, 380 #135
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
package g0301_0400.s0374_guess_number_higher_or_lower; | ||
|
||
// #Easy #Binary_Search #Interactive | ||
|
||
/** | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please not use javadoc comments. |
||
* Forward declaration of guess API. | ||
* | ||
* @param num your guess | ||
* @return -1 if num is lower than the guess number 1 if num is higher than the guess number | ||
* otherwise return 0 int guess(int num); | ||
*/ | ||
public class Solution { | ||
public int guessNumber(int n) { | ||
int left = 1; | ||
int right = n; | ||
int mid; | ||
while (left <= right) { | ||
mid = left + (right - left) / 2; | ||
if (guess(mid) == 1) { | ||
left = mid + 1; | ||
} else if (guess(mid) == -1) { | ||
right = mid - 1; | ||
} else { | ||
return mid; | ||
} | ||
} | ||
return -1; | ||
} | ||
|
||
// Assume we pick 7 | ||
private int guess(int num) { | ||
return Integer.compare(7, num); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
374\. Guess Number Higher or Lower | ||
|
||
Easy | ||
|
||
We are playing the Guess Game. The game is as follows: | ||
|
||
I pick a number from `1` to `n`. You have to guess which number I picked. | ||
|
||
Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess. | ||
|
||
You call a pre-defined API `int guess(int num)`, which returns 3 possible results: | ||
|
||
* `-1`: The number I picked is lower than your guess (i.e. `pick < num`). | ||
* `1`: The number I picked is higher than your guess (i.e. `pick > num`). | ||
* `0`: The number I picked is equal to your guess (i.e. `pick == num`). | ||
|
||
Return _the number that I picked_. | ||
|
||
**Example 1:** | ||
|
||
**Input:** n = 10, pick = 6 | ||
|
||
**Output:** 6 | ||
|
||
**Example 2:** | ||
|
||
**Input:** n = 1, pick = 1 | ||
|
||
**Output:** 1 | ||
|
||
**Example 3:** | ||
|
||
**Input:** n = 2, pick = 1 | ||
|
||
**Output:** 1 | ||
|
||
**Example 4:** | ||
|
||
**Input:** n = 2, pick = 2 | ||
|
||
**Output:** 2 | ||
|
||
**Constraints:** | ||
|
||
* <code>1 <= n <= 2<sup>31</sup> - 1</code> | ||
* `1 <= pick <= n` |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
package g0301_0400.s0378_kth_smallest_element_in_a_sorted_matrix; | ||
|
||
// #Medium #Top_Interview_Questions #Array #Sorting #Binary_Search #Matrix #Heap_Priority_Queue | ||
|
||
public class Solution { | ||
public int kthSmallest(int[][] matrix, int k) { | ||
if (matrix == null || matrix.length == 0) { | ||
return -1; | ||
} | ||
int start = matrix[0][0]; | ||
int end = matrix[matrix.length - 1][matrix[0].length - 1]; | ||
// O(log(max-min)) time | ||
while (start + 1 < end) { | ||
int mid = start + (end - start) / 2; | ||
if (countLessEqual(matrix, mid) < k) { | ||
// look towards end | ||
start = mid; | ||
} else { | ||
// look towards start | ||
end = mid; | ||
} | ||
} | ||
|
||
// leave only with start and end, one of them must be the answer | ||
// try to see if start fits the criteria first | ||
if (countLessEqual(matrix, start) >= k) { | ||
return start; | ||
} else { | ||
return end; | ||
} | ||
} | ||
|
||
// countLessEqual | ||
// O(n) Time | ||
private int countLessEqual(int[][] matrix, int target) { | ||
// binary elimination from top right | ||
int row = 0; | ||
int col = matrix[0].length - 1; | ||
int count = 0; | ||
while (row < matrix.length && col >= 0) { | ||
if (matrix[row][col] == target) { | ||
// get the count in current row | ||
count += col + 1; | ||
row++; | ||
} else if (matrix[row][col] > target) { | ||
// eliminate the current col | ||
col--; | ||
} else { | ||
// get the count in current row | ||
count += col + 1; | ||
row++; | ||
} | ||
} | ||
return count; | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
378\. Kth Smallest Element in a Sorted Matrix | ||
|
||
Medium | ||
|
||
Given an `n x n` `matrix` where each of the rows and columns is sorted in ascending order, return _the_ <code>k<sup>th</sup></code> _smallest element in the matrix_. | ||
|
||
Note that it is the <code>k<sup>th</sup></code> smallest element **in the sorted order**, not the <code>k<sup>th</sup></code> **distinct** element. | ||
|
||
You must find a solution with a memory complexity better than <code>O(n<sup>2</sup>)</code>. | ||
|
||
**Example 1:** | ||
|
||
**Input:** matrix = \[\[1,5,9\],\[10,11,13\],\[12,13,15\]\], k = 8 | ||
|
||
**Output:** 13 | ||
|
||
**Explanation:** The elements in the matrix are \[1,5,9,10,11,12,13,**13**,15\], and the 8<sup>th</sup> smallest number is 13 | ||
|
||
**Example 2:** | ||
|
||
**Input:** matrix = \[\[-5\]\], k = 1 | ||
|
||
**Output:** -5 | ||
|
||
**Constraints:** | ||
|
||
* `n == matrix.length == matrix[i].length` | ||
* `1 <= n <= 300` | ||
* <code>-10<sup>9</sup> <= matrix[i][j] <= 10<sup>9</sup></code> | ||
* All the rows and columns of `matrix` are **guaranteed** to be sorted in **non-decreasing order**. | ||
* <code>1 <= k <= n<sup>2</sup></code> | ||
|
||
**Follow up:** | ||
|
||
* Could you solve the problem with a constant memory (i.e., `O(1)` memory complexity)? | ||
* Could you solve the problem in `O(n)` time complexity? The solution may be too advanced for an interview but you may find reading [this paper](http://www.cse.yorku.ca/~andy/pubs/X+Y.pdf) fun. |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
package g0301_0400.s0380_insert_delete_getrandom_o1; | ||
|
||
import java.util.*; | ||
|
||
class RandomizedSet { | ||
private final Random rand; | ||
private final List<Integer> list; | ||
private final Map<Integer, Integer> map; | ||
|
||
/** Initialize your data structure here. */ | ||
public RandomizedSet() { | ||
this.rand = new Random(); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
this.list = new ArrayList<>(); | ||
this.map = new HashMap<>(); | ||
} | ||
|
||
/** | ||
* Inserts a value to the set. Returns true if the set did not already contain the specified | ||
* element. | ||
*/ | ||
public boolean insert(int val) { | ||
if (this.map.containsKey(val)) { | ||
return false; | ||
} | ||
this.list.add(val); | ||
this.map.put(val, list.size() - 1); | ||
return true; | ||
} | ||
|
||
/** Removes a value from the set. Returns true if the set contained the specified element. */ | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It may be a simple comment, not javadoc. |
||
public boolean remove(int val) { | ||
if (!this.map.containsKey(val)) { | ||
return false; | ||
} | ||
int index = this.map.get(val); | ||
if (index == this.list.size() - 1) { | ||
this.list.remove(index); | ||
this.map.remove(val); | ||
return true; | ||
} | ||
int value = list.get(list.size() - 1); | ||
this.list.set(index, value); | ||
this.list.remove(this.list.size() - 1); | ||
this.map.remove(val); | ||
this.map.put(value, index); | ||
return true; | ||
} | ||
|
||
/** Get a random element from the set. */ | ||
public int getRandom() { | ||
return this.list.get(rand.nextInt(list.size())); | ||
} | ||
} | ||
|
||
/** | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please not use javadoc comments to avoid reformatting block. |
||
* Your RandomizedSet object will be instantiated and called as such: RandomizedSet obj = new | ||
* RandomizedSet(); boolean param_1 = obj.insert(val); boolean param_2 = obj.remove(val); int | ||
* param_3 = obj.getRandom(); | ||
*/ |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
380\. Insert Delete GetRandom O(1) | ||
|
||
Medium | ||
|
||
Implement the `RandomizedSet` class: | ||
|
||
* `RandomizedSet()` Initializes the `RandomizedSet` object. | ||
* `bool insert(int val)` Inserts an item `val` into the set if not present. Returns `true` if the item was not present, `false` otherwise. | ||
* `bool remove(int val)` Removes an item `val` from the set if present. Returns `true` if the item was present, `false` otherwise. | ||
* `int getRandom()` Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the **same probability** of being returned. | ||
|
||
You must implement the functions of the class such that each function works in **average** `O(1)` time complexity. | ||
|
||
**Example 1:** | ||
|
||
**Input** \["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"\] \[\[\], \[1\], \[2\], \[2\], \[\], \[1\], \[2\], \[\]\] | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It looks like multiline block. |
||
|
||
**Output:** \[null, true, false, true, 2, true, false, 2\] | ||
|
||
**Explanation:** | ||
|
||
RandomizedSet randomizedSet = new RandomizedSet(); | ||
randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully. | ||
randomizedSet.remove(2); // Returns false as 2 does not exist in the set. | ||
randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains \[1,2\]. | ||
randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly. | ||
randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains \[2\]. | ||
randomizedSet.insert(2); // 2 was already in the set, so return false. | ||
randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2. | ||
|
||
**Constraints:** | ||
|
||
* <code>-2<sup>31</sup> <= val <= 2<sup>31</sup> - 1</code> | ||
* At most `2 * `<code>10<sup>5</sup></code> calls will be made to `insert`, `remove`, and `getRandom`. | ||
* There will be **at least one** element in the data structure when `getRandom` is called. |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
package g0301_0400.s0374_guess_number_higher_or_lower; | ||
|
||
import static org.hamcrest.CoreMatchers.equalTo; | ||
import static org.hamcrest.MatcherAssert.assertThat; | ||
|
||
import org.junit.jupiter.api.Test; | ||
|
||
class SolutionTest { | ||
@Test | ||
void guessNumber() { | ||
assertThat(new Solution().guessNumber(10), equalTo(7)); | ||
} | ||
|
||
@Test | ||
void guessNumber2() { | ||
assertThat(new Solution().guessNumber(1), equalTo(-1)); | ||
} | ||
|
||
@Test | ||
void guessNumber3() { | ||
assertThat(new Solution().guessNumber(2), equalTo(-1)); | ||
} | ||
|
||
@Test | ||
void guessNumber4() { | ||
assertThat(new Solution().guessNumber(6), equalTo(-1)); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
package g0301_0400.s0378_kth_smallest_element_in_a_sorted_matrix; | ||
|
||
import static org.hamcrest.CoreMatchers.equalTo; | ||
import static org.hamcrest.MatcherAssert.assertThat; | ||
|
||
import org.junit.jupiter.api.Test; | ||
|
||
class SolutionTest { | ||
@Test | ||
void kthSmallest() { | ||
assertThat( | ||
new Solution().kthSmallest(new int[][] {{1, 5, 9}, {10, 11, 13}, {12, 13, 15}}, 8), | ||
equalTo(13)); | ||
} | ||
|
||
@Test | ||
void kthSmallest2() { | ||
assertThat(new Solution().kthSmallest(new int[][] {{-5}}, 1), equalTo(-5)); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
package g0301_0400.s0380_insert_delete_getrandom_o1; | ||
|
||
import static org.hamcrest.CoreMatchers.equalTo; | ||
import static org.hamcrest.MatcherAssert.assertThat; | ||
|
||
import java.util.ArrayList; | ||
import java.util.Arrays; | ||
import java.util.List; | ||
import org.junit.jupiter.api.Test; | ||
|
||
class RandomizedSetTest { | ||
@Test | ||
void RandomizedSet() { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please name method from non capital letter. |
||
List<String> result = new ArrayList<>(); | ||
RandomizedSet randomizedSet = null; | ||
result.add(randomizedSet + ""); | ||
randomizedSet = new RandomizedSet(); | ||
result.add(randomizedSet.insert(1) + ""); | ||
result.add(randomizedSet.remove(2) + ""); | ||
result.add(randomizedSet.insert(2) + ""); | ||
int random = randomizedSet.getRandom(); | ||
result.add(random + ""); | ||
result.add(randomizedSet.remove(1) + ""); | ||
result.add(randomizedSet.insert(2) + ""); | ||
result.add(randomizedSet.getRandom() + ""); | ||
List<String> expected = | ||
new ArrayList<>( | ||
Arrays.asList("null", "true", "false", "true", "1", "true", "false", "2")); | ||
List<String> expected2 = | ||
new ArrayList<>( | ||
Arrays.asList("null", "true", "false", "true", "2", "true", "false", "2")); | ||
if (random == 1) { | ||
assertThat(result, equalTo(expected)); | ||
} else { | ||
assertThat(result, equalTo(expected2)); | ||
} | ||
} | ||
} |