题目地址:搜索插入位置
心想这也太简单:
class Solution {
public int searchInsert(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
if (nums[i] == target || nums[i] > target)
return i;
}
return nums.length;
}
}
结果:
忘了一种比较高效的算法:二分查找
class Solution {
public int searchInsert(int[] nums, int target) {
int left = 0;
int right = nums.length-1;
while(left <= right){
int mid = (left+right)/2;
if(nums[mid] == target)
return mid;
else if(nums[mid] < target)
left = mid+1;
else
right = mid-1;
}
return left;
}
}
结果:
似乎提升了一点点……