81. Search in Rotated Sorted Array II
same as 33, but data has duplicate numbers
just add this judgement, cant solve duplicate problems
// ๅค้ๅๆขไปถ, ๅ ็บ็ฝๆถๅฐ start, end , ๆไปฅ้ฝ่ฆ่็
if (nums[start] == nums[mid] && nums[mid] == nums[end]) {
start++;
end--;
}
// ๅ
ถๅฏฆๅชๅฏซ้ๆจฃไนๅฏไปฅ
if (nums[mid] == nums[end]) {
end--;
}
time: O(logn)
space: O(1)
class Solution {
public boolean search(int[] nums, int target) {
int start = 0;
int end = nums.length - 1;
while (start <= end) {
int mid = (start + end) >> 1;
if (nums[mid] == target) return true;
// ๅค้ๅๆขไปถ
if (nums[start] == nums[mid] && nums[mid] == nums[end]) {
start++;
end--;
} else if (nums[start] <= nums[mid]) {
if (nums[start] <= target && target <= nums[mid]) { // in left
end = mid - 1;
} else {
start = mid + 1;
}
} else {
if (nums[mid] <= target && target <= nums[end]) {
start = mid + 1;
} else {
end = mid - 1;
}
}
}
return false;
}
}
ๆๆณ้ๅๅฏซๆณ่ท 154 ๆฏ่ผไธ่ด
class Solution {
public boolean search(int[] nums, int target) {
int start = 0;
int end = nums.length - 1;
while (start <= end) {
int mid = (start + end) >> 1;
if (nums[mid] == target) return true;
if (nums[start] < nums[mid]) {
if (nums[start] <= target && target <= nums[mid]) { // in left
end = mid - 1;
} else {
start = mid + 1;
}
} else if (nums[start] > nums[mid]) {
if (nums[mid] <= target && target <= nums[end]) {
start = mid + 1;
} else {
end = mid - 1;
}
} else {
start++;
}
}
return false;
}
}
Last updated