704. 二分查找
自己看到题目的第一想法
Below is the first time I think about the problem. Accidentally, it is using the 左闭右闭 modal. My way to tackle the problem is to narrow down search space, making sure that the new search space does not include the item I compared before. But I was still confused to whether I should use left <= right or left < right
class Solution {
// 左闭右闭
public int search(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left <= right) {
int middle = (left + right) / 2;
if (target == nums[middle]) {
return middle;
} else if (target < nums[middle]) {
right = middle - 1;
} else if (target > nums[middle]) {
left = middle + 1;
}
}
return -1;
}
}
看完代码随想录之后的想法
Teacher defines a very good mental model 左闭右闭 [left, right], 左闭右开 [left, right)
- 左闭右闭 means both left and right is included
- 左闭右开 means only left is included but not right
class Solution {
public int search(int[] nums, int target) {
// 左閉右開
int left = 0, right = nums.length;
while (left < right) {
int middle = (left + right) / 2;
if (target == nums[middle]) {
return middle;
} else if (target < nums[middle]) {
right = middle;
} else if (target > nums[middle]) {
left = middle + 1;
}
}
return -1;
}
}
Because it is 左閉右開, right cannot be equal to left. Therefore, the condition should be left < right. Also, when target < nums[middle], right is not included as well so can use middle directly.
27. 移除元素
自己看到题目的第一想法
暴力的解法 for this question is in order to delete an item from an array, I need to move item 1 step forward. The time complexity is O(n^2). But the space complexity is O(1) which meet the criteria of the question
class Solution {
public int removeElement(int[] nums, int val) {
// Brute Force
// Cannot allocate extra space
int end = nums.length;
int i = 0;
while (i < end) {
if (nums[i] == val) {
for (int j = i + 1; j < end; j++) {
nums[i] = nums[j];
}
end--;
} else {
i++;
}
}
return end;
}
}
I then try 双指针法, one pointer point to start and one pointer point to end. But it doesn't work and I have to look to answer.
看完代码随想录之后的想法
It turns out that the answer have two pointers both pointing to the start. One pointer is fast pointer and one is slow pointer.
- Fast Pointer: loop through all elements in array
- Slow Pointer: representing the new array
By using two pointers, the time complexity can improved to O(n) and space complexity is still O(1)
class Solution {
public int removeElement(int[] nums, int val) {
int slow = 0;
for (int fast = 0; fast < nums.length; fast++) {
if (nums[fast] != val) {
nums[slow] = nums[fast];
slow++;
}
}
return slow;
}
}