Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 909f90b

Browse files
Added tasks 374, 378, 380.
1 parent f9d0f57 commit 909f90b

File tree

9 files changed

+356
-0
lines changed

9 files changed

+356
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package g0301_0400.s0374_guess_number_higher_or_lower;
2+
3+
// #Easy #Binary_Search #Interactive
4+
5+
/**
6+
* Forward declaration of guess API.
7+
*
8+
* @param num your guess
9+
* @return -1 if num is lower than the guess number 1 if num is higher than the guess number
10+
* otherwise return 0 int guess(int num);
11+
*/
12+
public class Solution {
13+
public int guessNumber(int n) {
14+
int left = 1;
15+
int right = n;
16+
int mid;
17+
while (left <= right) {
18+
mid = left + (right - left) / 2;
19+
if (guess(mid) == 1) {
20+
left = mid + 1;
21+
} else if (guess(mid) == -1) {
22+
right = mid - 1;
23+
} else {
24+
return mid;
25+
}
26+
}
27+
return -1;
28+
}
29+
30+
// Assume we pick 7
31+
private int guess(int num) {
32+
return Integer.compare(7, num);
33+
}
34+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
374\. Guess Number Higher or Lower
2+
3+
Easy
4+
5+
We are playing the Guess Game. The game is as follows:
6+
7+
I pick a number from `1` to `n`. You have to guess which number I picked.
8+
9+
Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.
10+
11+
You call a pre-defined API `int guess(int num)`, which returns 3 possible results:
12+
13+
* `-1`: The number I picked is lower than your guess (i.e. `pick < num`).
14+
* `1`: The number I picked is higher than your guess (i.e. `pick > num`).
15+
* `0`: The number I picked is equal to your guess (i.e. `pick == num`).
16+
17+
Return _the number that I picked_.
18+
19+
**Example 1:**
20+
21+
**Input:** n = 10, pick = 6
22+
23+
**Output:** 6
24+
25+
**Example 2:**
26+
27+
**Input:** n = 1, pick = 1
28+
29+
**Output:** 1
30+
31+
**Example 3:**
32+
33+
**Input:** n = 2, pick = 1
34+
35+
**Output:** 1
36+
37+
**Example 4:**
38+
39+
**Input:** n = 2, pick = 2
40+
41+
**Output:** 2
42+
43+
**Constraints:**
44+
45+
* <code>1 <= n <= 2<sup>31</sup> - 1</code>
46+
* `1 <= pick <= n`
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package g0301_0400.s0378_kth_smallest_element_in_a_sorted_matrix;
2+
3+
// #Medium #Top_Interview_Questions #Array #Sorting #Binary_Search #Matrix #Heap_Priority_Queue
4+
5+
public class Solution {
6+
public int kthSmallest(int[][] matrix, int k) {
7+
if (matrix == null || matrix.length == 0) {
8+
return -1;
9+
}
10+
int start = matrix[0][0];
11+
int end = matrix[matrix.length - 1][matrix[0].length - 1];
12+
// O(log(max-min)) time
13+
while (start + 1 < end) {
14+
int mid = start + (end - start) / 2;
15+
if (countLessEqual(matrix, mid) < k) {
16+
// look towards end
17+
start = mid;
18+
} else {
19+
// look towards start
20+
end = mid;
21+
}
22+
}
23+
24+
// leave only with start and end, one of them must be the answer
25+
// try to see if start fits the criteria first
26+
if (countLessEqual(matrix, start) >= k) {
27+
return start;
28+
} else {
29+
return end;
30+
}
31+
}
32+
33+
// countLessEqual
34+
// O(n) Time
35+
private int countLessEqual(int[][] matrix, int target) {
36+
// binary elimination from top right
37+
int row = 0;
38+
int col = matrix[0].length - 1;
39+
int count = 0;
40+
while (row < matrix.length && col >= 0) {
41+
if (matrix[row][col] <= target) {
42+
// get the count in current row
43+
count += col + 1;
44+
row++;
45+
} else if (matrix[row][col] > target) {
46+
// eliminate the current col
47+
col--;
48+
}
49+
}
50+
return count;
51+
}
52+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
378\. Kth Smallest Element in a Sorted Matrix
2+
3+
Medium
4+
5+
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_.
6+
7+
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.
8+
9+
You must find a solution with a memory complexity better than <code>O(n<sup>2</sup>)</code>.
10+
11+
**Example 1:**
12+
13+
**Input:** matrix = \[\[1,5,9\],\[10,11,13\],\[12,13,15\]\], k = 8
14+
15+
**Output:** 13
16+
17+
**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
18+
19+
**Example 2:**
20+
21+
**Input:** matrix = \[\[-5\]\], k = 1
22+
23+
**Output:** -5
24+
25+
**Constraints:**
26+
27+
* `n == matrix.length == matrix[i].length`
28+
* `1 <= n <= 300`
29+
* <code>-10<sup>9</sup> <= matrix[i][j] <= 10<sup>9</sup></code>
30+
* All the rows and columns of `matrix` are **guaranteed** to be sorted in **non-decreasing order**.
31+
* <code>1 <= k <= n<sup>2</sup></code>
32+
33+
**Follow up:**
34+
35+
* Could you solve the problem with a constant memory (i.e., `O(1)` memory complexity)?
36+
* 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.
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package g0301_0400.s0380_insert_delete_getrandom_o1;
2+
3+
// #Medium #Top_Interview_Questions #Array #Hash_Table #Math #Design #Randomized
4+
5+
import java.security.SecureRandom;
6+
import java.util.ArrayList;
7+
import java.util.HashMap;
8+
import java.util.List;
9+
import java.util.Map;
10+
11+
public class RandomizedSet {
12+
private final SecureRandom rand;
13+
private final List<Integer> list;
14+
private final Map<Integer, Integer> map;
15+
16+
// Initialize your data structure here.
17+
public RandomizedSet() {
18+
this.rand = new SecureRandom();
19+
this.list = new ArrayList<>();
20+
this.map = new HashMap<>();
21+
}
22+
23+
// Inserts a value to the set. Returns true if the set did not already contain the specified
24+
// element.
25+
26+
public boolean insert(int val) {
27+
if (this.map.containsKey(val)) {
28+
return false;
29+
}
30+
this.list.add(val);
31+
this.map.put(val, list.size() - 1);
32+
return true;
33+
}
34+
35+
// Removes a value from the set. Returns true if the set contained the specified element.
36+
public boolean remove(int val) {
37+
if (!this.map.containsKey(val)) {
38+
return false;
39+
}
40+
int index = this.map.get(val);
41+
if (index == this.list.size() - 1) {
42+
this.list.remove(index);
43+
this.map.remove(val);
44+
return true;
45+
}
46+
int value = list.get(list.size() - 1);
47+
this.list.set(index, value);
48+
this.list.remove(this.list.size() - 1);
49+
this.map.remove(val);
50+
this.map.put(value, index);
51+
return true;
52+
}
53+
54+
// Get a random element from the set.
55+
public int getRandom() {
56+
return this.list.get(rand.nextInt(list.size()));
57+
}
58+
}
59+
60+
/*
61+
* Your RandomizedSet object will be instantiated and called as such: RandomizedSet obj = new
62+
* RandomizedSet(); boolean param_1 = obj.insert(val); boolean param_2 = obj.remove(val); int
63+
* param_3 = obj.getRandom();
64+
*/
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
380\. Insert Delete GetRandom O(1)
2+
3+
Medium
4+
5+
Implement the `RandomizedSet` class:
6+
7+
* `RandomizedSet()` Initializes the `RandomizedSet` object.
8+
* `bool insert(int val)` Inserts an item `val` into the set if not present. Returns `true` if the item was not present, `false` otherwise.
9+
* `bool remove(int val)` Removes an item `val` from the set if present. Returns `true` if the item was present, `false` otherwise.
10+
* `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.
11+
12+
You must implement the functions of the class such that each function works in **average** `O(1)` time complexity.
13+
14+
**Example 1:**
15+
16+
**Input**
17+
18+
\["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"\]
19+
\[\[\], \[1\], \[2\], \[2\], \[\], \[1\], \[2\], \[\]\]
20+
21+
**Output:** \[null, true, false, true, 2, true, false, 2\]
22+
23+
**Explanation:**
24+
25+
RandomizedSet randomizedSet = new RandomizedSet();
26+
randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.
27+
randomizedSet.remove(2); // Returns false as 2 does not exist in the set.
28+
randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains \[1,2\].
29+
randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.
30+
randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains \[2\].
31+
randomizedSet.insert(2); // 2 was already in the set, so return false.
32+
randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.
33+
34+
**Constraints:**
35+
36+
* <code>-2<sup>31</sup> <= val <= 2<sup>31</sup> - 1</code>
37+
* At most `2 * `<code>10<sup>5</sup></code> calls will be made to `insert`, `remove`, and `getRandom`.
38+
* There will be **at least one** element in the data structure when `getRandom` is called.
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package g0301_0400.s0374_guess_number_higher_or_lower;
2+
3+
import static org.hamcrest.CoreMatchers.equalTo;
4+
import static org.hamcrest.MatcherAssert.assertThat;
5+
6+
import org.junit.jupiter.api.Test;
7+
8+
class SolutionTest {
9+
@Test
10+
void guessNumber() {
11+
assertThat(new Solution().guessNumber(10), equalTo(7));
12+
}
13+
14+
@Test
15+
void guessNumber2() {
16+
assertThat(new Solution().guessNumber(1), equalTo(-1));
17+
}
18+
19+
@Test
20+
void guessNumber3() {
21+
assertThat(new Solution().guessNumber(2), equalTo(-1));
22+
}
23+
24+
@Test
25+
void guessNumber4() {
26+
assertThat(new Solution().guessNumber(6), equalTo(-1));
27+
}
28+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package g0301_0400.s0378_kth_smallest_element_in_a_sorted_matrix;
2+
3+
import static org.hamcrest.CoreMatchers.equalTo;
4+
import static org.hamcrest.MatcherAssert.assertThat;
5+
6+
import org.junit.jupiter.api.Test;
7+
8+
class SolutionTest {
9+
@Test
10+
void kthSmallest() {
11+
assertThat(
12+
new Solution().kthSmallest(new int[][] {{1, 5, 9}, {10, 11, 13}, {12, 13, 15}}, 8),
13+
equalTo(13));
14+
}
15+
16+
@Test
17+
void kthSmallest2() {
18+
assertThat(new Solution().kthSmallest(new int[][] {{-5}}, 1), equalTo(-5));
19+
}
20+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package g0301_0400.s0380_insert_delete_getrandom_o1;
2+
3+
import static org.hamcrest.CoreMatchers.equalTo;
4+
import static org.hamcrest.MatcherAssert.assertThat;
5+
6+
import java.util.ArrayList;
7+
import java.util.Arrays;
8+
import java.util.List;
9+
import org.junit.jupiter.api.Test;
10+
11+
class RandomizedSetTest {
12+
@Test
13+
void randomizedSet() {
14+
List<String> result = new ArrayList<>();
15+
RandomizedSet randomizedSet = null;
16+
result.add(randomizedSet + "");
17+
randomizedSet = new RandomizedSet();
18+
result.add(randomizedSet.insert(1) + "");
19+
result.add(randomizedSet.remove(2) + "");
20+
result.add(randomizedSet.insert(2) + "");
21+
int random = randomizedSet.getRandom();
22+
result.add(random + "");
23+
result.add(randomizedSet.remove(1) + "");
24+
result.add(randomizedSet.insert(2) + "");
25+
result.add(randomizedSet.getRandom() + "");
26+
List<String> expected =
27+
new ArrayList<>(
28+
Arrays.asList("null", "true", "false", "true", "1", "true", "false", "2"));
29+
List<String> expected2 =
30+
new ArrayList<>(
31+
Arrays.asList("null", "true", "false", "true", "2", "true", "false", "2"));
32+
if (random == 1) {
33+
assertThat(result, equalTo(expected));
34+
} else {
35+
assertThat(result, equalTo(expected2));
36+
}
37+
}
38+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /