Leetcode 35 Search Insert Position

HowieLee59發表於2018-11-01

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;
    }
};

 

相關文章