35. Search Insert Position, insertposition

Source: Internet
Author: User

35. Search Insert Position, insertposition

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it wocould 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

 

Search for a value in an sorted array. If a value exists, the corresponding value is returned. If no value exists, the index that can be inserted into the array is returned,In fact, it is to find the first subscript that is greater than or equal to the target value..

 

 1 class Solution { 2 public: 3     int searchInsert(vector<int>& nums, int target) { 4         int low = 0; 5         int high = nums.size()-1; 6          7         int mid = 0; 8         while(low <= high){ 9             mid = low + (high-low)/2;10             if(target <= nums[mid]){11                 high = mid-1;12             }else{13                 low = mid+1;14             }15         }16         return low;17     }18 };

 

Explanation:

1. The condition is target <= nums [mid], which means that if the target is smaller than or equal to the middle value, search for the target in the left half. For example, in {1, 2, 2, 4, 8, 10}, find 2. In the first step, low = 0, high = 6, obtain mid = 3, target <= a [3], search for the subscript {1, 2.

2. The first step to terminate is: low = high, and mid = low. At this time, if target <= nums [mid], high changes, and low points to the current element, it is the element that meets the requirements. If target> nums [mid], low changes, and low points to the next element of mid.

3. If the key is greater than the last element of the array, low changes to nums. size (). That is, if no element is greater than the key, nums. size () is returned ().

 

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.