[Leetcode]35.search Insert Position

Source: Internet
Author: User

"title"

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would is if it were inserted in order.

Assume no duplicates in the array.

Here is 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

"Analysis"

This problem is relatively simple, that is, two-point search. The idea is to take the middle each time, if equal to the goal is to return, or according to the size of the relationship cut half. Thus the algorithm complexity is O (logn), Spatial complexity O (1).

"Code"
/********************************** Date: 2015-01-24* sjf0115* title: 35.Search Insert position* URL: Https://oj.leetcode. com/problems/search-insert-position/* Result: ac* Source: leetcode* Blog: **********************************/#include < Iostream> #include <vector>using namespace Std;class solution {public:int searchinsert (int a[], int n, int tar        Get) {if (n <= 0) {return-1;        }//if int start = 0,end = N-1;            Two-point lookup while (start <= end) {int mid = start + ((End-start) >> 1);            Target to find if (a[mid] = = target) {return mid;            }//if//target in the left half part else if (A[mid] > target) {end = Mid-1;            }//else//target in right half else{start = mid + 1;    }//else}//while//target element not found then find the insertion position return start;//end + 1}};int main () {solution solution;    int a[] = {1,3,5,6}; Intn = 4;    int target = 0;    int result = Solution.searchinsert (a,n,target);    Output cout<<result<<endl; return 0;}





[Leetcode]35.search Insert Position

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.