Leetcode 算法习题 第五周

35. 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.
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

题目大意:

将给定的数插入有序数组,返回插入对应位置的数组下标

我的解答:

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


        }
       return nums.size();


    }
};

你可能感兴趣的:(Leetcode 算法习题 第五周)