1. 程式人生 > >35. Search Insert Position(python+cpp)

35. Search Insert Position(python+cpp)

題目:

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

解釋:
二分查詢問題,事實上就是實現bisct.bisct_left(),注意不是bisect.bisect(),因為如果數字在陣列中已經出現了的話bisect.bisect()返回的是可以插入的位置,有可能返回的是數字出現的位置的後一個位置,但是這裡題目要求返回的是數字的位置。(即數字在陣列中第一次出現的位置)
用庫函式實現:
python程式碼:

import bisect
class
Solution(object): def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ return bisect.bisect_left(nums,target)

c++程式碼:

#include<algorithm>
using namespace std;
class Solution {
public:
    int
searchInsert(vector<int>& nums, int target) { return lower_bound(nums.begin(),nums.end(),target)-nums.begin(); } };

手動實現二分查詢,注意這裡要求是<=,最終返回的是left,如果是<的話,最終指向的可能是比其小的位置,也可能是比起大的位置。
python程式碼:

import bisect
class Solution(object):
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        left,right=0,len(nums)-1
        while left<=right:
            mid=left+(right-left)/2
            if nums[mid]==target:
                return mid
            else:
                if nums[mid]<target:
                    left=mid+1
                else:
                    right=mid-1
        return left

c++程式碼:

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int left=0;
        int right=nums.size()-1;
        while (left<=right)
        {
            int mid=left+(right-left)/2;
            if (nums[mid]==target)
                return mid;
            else if (nums[mid]<target)
                left=mid+1;
            else
                right=mid-1;
        }
        return left; 
    }
};

總結:
反正二分查詢有很多細節需要注意,比如說這裡需要注意的是使用<=和返回left,注意,經典的二分查詢問題也是<=