leetcode35——Search Insert Position

原创 2018年04月16日 14:33:32

题目大意:找到目标数字应该插入所给不重复升序数组的下标位置

分析:二分搜索。普通遍历也可以,二分查找的效率更高。

代码:

方法一:普通遍历

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

};

方法二:二分查找

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

[LeetCode]35.Search Insert Position

【题目】 Given a sorted array and a target value, return the index if the target is found. If not, ...
  • SunnyYoona
  • SunnyYoona
  • 2015-01-24 15:07:12
  • 1501

LeetCode 35 Search Insert Position (C,C++,Java,Python)

Problem: Given a sorted array and a target value, return the index if the target is found. If n...
  • runningtortoises
  • runningtortoises
  • 2015-05-18 20:33:01
  • 1166

LeetCode35——Search Insert Position

LeetCode35——Search Insert Position 题意: 给定一个target,和有序序列,如果target在序列中,则返回其索引,否则给出当插入target且不改变序列性质时...
  • zhangxiao93
  • zhangxiao93
  • 2015-10-15 22:01:06
  • 739

Leetcode35 Search Insert Position

Search Insert Position Given a sorted array and a target value, return the index if the target is ...
  • u011513853
  • u011513853
  • 2015-07-28 19:11:49
  • 209

Leetcode35: Search Insert Position

Given a sorted array and a target value, return the index if the target is found. If not, return the...
  • sea_px
  • sea_px
  • 2016-10-29 22:06:30
  • 51

[LeetCode35]Search Insert Position

Given a sorted array and a target value, return the index if the target is found. If not, return the...
  • sbitswc
  • sbitswc
  • 2014-06-16 04:11:49
  • 627

leetcode35~Search Insert Position

Given a sorted array and a target value, return the index if the target is found. If not, return the...
  • stone_yw
  • stone_yw
  • 2017-03-09 17:09:19
  • 123

leetcode35: Search Insert Position

要求: Given a sorted array and a target value, return the index if the target is found. If not, ret...
  • sinat_35425429
  • sinat_35425429
  • 2016-12-12 18:58:39
  • 61

python实现 LeetCode35——Search Insert Position

自己开始写的代码,不过因为要多判断一次第一个数字,所以感觉不是很整洁,不过也通过了。class Solution(object): def searchInsert(self, nums, t...
  • xiaoling_000666
  • xiaoling_000666
  • 2018-03-21 18:57:45
  • 3

Search Insert Position -- LeetCode

原题链接: http://oj.leetcode.com/problems/search-insert-position/  这道题比较简单,就是二分查找。思路就是每次取中间,如果等于目标即返回,否则...
  • linhuanmars
  • linhuanmars
  • 2014-03-02 07:40:19
  • 12973
收藏助手
不良信息举报
您举报文章:leetcode35——Search Insert Position
举报原因:
原因补充:

(最多只允许输入30个字)