35. Search Insert Position

来源:互联网 发布:smart forfour 知乎 编辑:程序博客网 时间:2024/06/06 02:54

问题描述

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.
题目链接:35. Search Insert Position

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


思路分析

要求找到指定整数在数组中应该存放的位置,如果与数组中已存在的值相等,那么就返回这个值的index;如果没有相等的值,则放回应该存放的位置。思路是遍历数组,找到比target大的值,就是target应该存放的位置;如果target比所有的元素都大,就把它放在最后一位

代码

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

时间复杂度:O(n) //n为nums的元素个数。


反思

很基础的题目啦,还是很顺利的,不过还有更快的 binary search 的方法,时间复杂度是O(logn)。代码:

class Solution {public:    int searchInsert(vector<int>& nums, int target) {        int high = nums.size()-1, low = 0, mid = (low + high)/2;        while(low <= high){            mid = (low + high)/2;            if (nums[mid] < target)               low = mid + 1;            else               high = mid - 1;        }            return low;    }};
原创粉丝点击