search-insert-position

原创 2018年04月17日 09:37:46

题目描述

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(int A[], int n, int target) {
        int index=0;
        for(;index<n;index++)
        {
            if(target<=A[index]) break;
        }
        return index;
    }
};

Search Insert Position三种方法解析

今天做的是LeetCode35,寻找给定元素在数组中的位置,如果没有此元素的话给出插入的位置 基本解法很简单: public int searchInsert(int[] nums, int tar...
  • yinyanting1
  • yinyanting1
  • 2017-02-23 15:21:26
  • 108

Python - Search Insert Position

【LeetCode with Python】 Search Insert Position  标签: LeetCodeLeetCode with PythonPython 2014-0...
  • screaming
  • screaming
  • 2016-01-16 19:52:32
  • 242

leetcode — search-insert-position

/** * Source : https://oj.leetcode.com/problems/search-insert-position/ * * Created by lverpeng o...
  • gesanghuakaisunshine
  • gesanghuakaisunshine
  • 2018-02-28 09:09:27
  • 3

《leetcode》search-insert-position

题目描述Given a sorted array and a target value, return the index if the target is found. If not, return...
  • wickedvalley
  • wickedvalley
  • 2017-08-31 13:25:40
  • 101

search-insert-position/search-in-rotated-sorted-array/search-in-rotated-sorted-array ii

题目一:search-insert-position Given a sorted array and a target value, return the index if the target ...
  • ldw662523
  • ldw662523
  • 2017-12-03 13:56:22
  • 45

search-insert-position/search-for-a-range/search-in-rotated-sorted-array

题目一:search-insert-position(注意:返回的是low) Given a sorted array and a target value, return the index if...
  • ldw662523
  • ldw662523
  • 2018-01-21 11:28:10
  • 190

https://leetcode.com/problems/search-insert-position/

https://leetcode.com/problems/search-insert-position/ 依然二分法 如果能找到直接返回index 如果找不到最后会逼近到s 那么target就...
  • le_chateau
  • le_chateau
  • 2015-05-23 13:10:28
  • 261

LeetCode解题报告--Search Insert Position

题目: Given a sorted array and a target value, return the index if the target is found. If not, retu...
  • github_27609763
  • github_27609763
  • 2015-12-04 16:58:11
  • 1115

Search Insert Position -- LeetCode

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

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