leetcode題記:Search Insert Position

編程語言:java

提交結果:

62 / 62 test cases passed.
Status: Accepted
Runtime: 3 ms
ps:運行時間和佔用空間打敗了100%的提交者,hhh

題目描述:
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

解題思路:

二分查找的思路;一看到這道題,筆者看到已排序的數組,查找一個數字,首先想到的是經典的二分查找;但是,應用之前,應該先想清楚這個題目與二分查找的不同之處,在套用二分查找之前,應該先想清楚這道題目和二分查找的區別;
與二分查找區別:查找的這個可能不存在與數組中;具體分爲三種情況;
第一,查找的數小於nums[0],比如[1,3,5,7]查找0
第二,查找的數大於nums[nums.length-1],比如[1,3,5,7]查找9
第三,查找的數介於nums兩個數中間,比如[1,3,5,7]查找6
針對這三種與二分查找的區別地方的思考:
針對第一點,可以開始之前加入一個if語句,判斷是否target小於nums[0],如果是,則返回0;
針對第二點,加入if語句,判斷是否target大於nums[nums.length-1].如果是,則返回nums.length.
針對第三點,比如[1,3,5,7]查找6,循環結束時的條件(left>-right-1),即(循環執行條件爲left<right-1)或者說已經明確找到某個值。所以當循環結束時,兩種情況,找到這個值,或者沒有找到。當沒有找到的時候,能夠確定這個值的位置一定在left索引與right索引之間。此時,left=rihgt-1,返回right索引即可。

難點:

找出與二分查找的區別之處並且給出相應的解決辦法;

代碼:

class Solution {
    public int searchInsert(int[] nums, int target) {
        int left = 0;
        int right = nums.length-1;
        int mid = (left+right)/2;


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


    }
}
發佈了40 篇原創文章 · 獲贊 35 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章