35. Search Insert Position

class Solution {
    public int searchInsert(int[] nums, int target) {
        int n = nums.length;
        for(int i = 0; i< n; i++){
            if(nums[n-1]<target)
                return n;
            else if(nums[i]>=target)
                return i;
            
                       
        }
        return 0;        
    }
}
别人的答案:
public int searchInsert(int[] nums, int target){
int i = 0;
for(int j = 0; j < nums.length; j++){
if(nums[i] < target){
i++;
}
}
return i;
}
二分法:
public class Solution {
public int searchInsert(int[] nums, int target) {
    int low = 0, high = nums.length;
    while(low < high) {
        int mid = low + (high - low) / 2;
        if(nums[mid] < target)
            low = mid + 1;
        else
            high = mid;
    }
    return low;
}
总结:看到别人的方法真的恍然大悟,做题不应该有想法就动笔,应该再思考思考的,有时候一些很小的令感就可以省下很多行代码 然后就是,有序数组的查找应该首先想到二分查找。
原文地址:https://www.cnblogs.com/ZoHy/p/12400681.html