Leetcode 35 Search Insert Position

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Neo233/article/details/83625873

Example 1:

Input: [1,3,5,6], 5
Output: 2

Example 2:

Input: [1,3,5,6], 2
Output: 1

Example 3:

Input: [1,3,5,6], 7
Output: 4

Example 4:

Input: [1,3,5,6], 0
Output: 0

这个题目的意思是找到target在数组中应该存放的地方,题目较简单,可以使用暴力或者是二分来做。

1)

class Solution {
    public int searchInsert(int[] nums, int target) {
        int len = nums.length;
        int i = 0;
        if(target <= nums[0]){
            return 0;
        }
        for(i = 0 ; i < len ; i++){
            if(nums[i] >= target){
                return i;
            }
        }
        return len;
    }
}

2)

public class Solution {
    public int searchInsert(int[] A, int target) {
        int left = A.length - 1;
        int right = 0;
        while(true){
            if(A[right] >= target){
                return right;
            }else if(A[left] < target){
                return left + 1;
            }
            int mid = right + (left - right) / 2;
            if(A[mid] <= target){
                right++;
            }else{
                left--;
            }
        }
    }
}

3)

class Solution {
public:
    int searchInsert(int A[], int n, int target) {
        int i=0;
        for(i=0;i<n;i++)
        {
            if(target <= A[i])
                return i;
        }
        return n;
    }
};

猜你喜欢

转载自blog.csdn.net/Neo233/article/details/83625873