1. 程式人生 > >【LEET-CODE】35. Search Insert Position

【LEET-CODE】35. Search Insert Position

Question:

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.

Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0

思路:

給定有序陣列,如果target在陣列中,返回索引標號,如果不在,則將target插入陣列並返回索引。

依次迴圈比較就好了,二分法可能會更快一點,懶所以沒寫。

Code:

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        if(nums.empty()){
                nums.push_back(target);
                return 0;
        }
        int x = 0;
        for(int i = 0 ;i < nums.size(); i++ ){
            if(nums[i]>=target){
                x = i;
                break;
            }
            if(i==nums.size()-1 && nums[i]<target){
                x = i+1;
                break;
            }
        }
        return x;
    }
};