35. Search Insert Position(二分法)

Search Insert Position

【題目】

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

(翻譯:給定一個排序數組和一個目標值,在數組中找到目標值,並返回其索引。如果目標值不存在於數組中,返回它將會被按順序插入的位置。

你可以假設數組中無重複元素。)

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

【分析】

這道題其實是二分法的變形,我在這裏寫了四種不同的二分法來實現題目要求,其中前兩種是同一個思路,後兩種是同一個思路:

寫法一:

public int searchInsert(int[] nums, int target) {
        int start = 0;
        int end = nums.length;
        while (start < end) {
            int mid = (start + end) >> 1;
            int midNum = nums[mid];
            if (midNum < target) {
                start = mid + 1;
            } else {
                end = mid;
            }
        }
        return start;
    }

寫法二:

public int searchInsert1(int[] nums, int target) {
        int start = 0;
        int end = nums.length - 1;
        int ans = nums.length;
        while (start <= end) {
            int mid = (start + end) >> 1;
            int midNum = nums[mid];

            if (midNum >= target) {
                ans = mid;
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        return ans;
    }

寫法三:

public int searchInsert2(int[] nums, int target) {
        int start = 0;
        int end = nums.length - 1;
        while (start + 1 < end) {
            int mid = (end - start) / 2 + start;
            if (target < nums[mid]) end = mid;
            else if (target > nums[mid]) start = mid;
            else return mid;
        }
        if (target <= nums[start]) {
            return start;
        } else if (target <= nums[end]) {
            return end;
        } else {
            return end + 1;
        }
    }

寫法四:

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


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章