题目
Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1.
Example 1:
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4
我的想法
二分法~
class Solution {
public int search(int[] nums, int target) {
if(nums == null || nums.length == 0) {
return -1;
}
int start = 0, end = nums.length - 1;
while(start <= end) {
int mid = (start + end) / 2;
if(target == nums[mid]) {
return mid;
}
if(target < nums[mid]) {
end = mid - 1;
}
if(target > nums[mid]) {
start = mid + 1;
}
}
return -1;
}
}
解答
jiuzhang solution:
写法不大一样,这里考虑了重复元素。注意这里用的是start + 1 < end
。在有相同元素例子中,比如:nums = [1, 1] target = 1
此时start = 0, end = 1, mid = 0
。如果题目是取寻找最后一个target,则当nums[mid] == target
,会使start = mid
,即还是等于0,一直死循环
class Solution {
public int search(int[] nums, int target) {
if(nums == null || nums.length == 0) {
return -1;
}
int start = 0, end = nums.length - 1;
//using start + 1 to avoid infinite loop
while(start + 1 < end) {
//avoid overflow
int mid = start + (end - start) / 2;
if(nums[mid] == target) {
//find the first target
end = mid;
} else if (nums[mid] < target) {
start = mid + 1;
} else {
end = mid - 1;
}
}
if(nums[start] == target) {
return start;
}
if(nums[end] == target) {
return end;
}
return -1;
}
}