Written question 48. Leetcode OJ (35)

Source: Internet
Author: User

This topic is still belong to the title of the search class, similar to the previous topic, the title of the request is given a target, in an ordered array to find the insertion order of the element, if present, return the element's subscript. This problem is more intuitive, so it is easier to do hands, it should be noted that the boundary conditions, such as:

(1). The target element is smaller than the smallest element in the sorted array

(2). The target element is larger than the largest element in the sorted array

Please look at the code, the code is still relatively clear

Class Solution {public:    int Searchinsert (vector<int>& nums, int target)     {        int len = Nums.size (); if (len = = 0) {return 0;} int left = 0;int right = Len-1;int mid = 0;if (Target > Nums[right]) {return right + 1;} while (left < right) {mid = left + (right-left)/2;if (nums[left] = = target) {return left;} if (nums[right] = = target) {return right;} if (nums[mid] = = target) {return mid;} if (Nums[mid] > target) {right = mid;} Else{left = mid + 1;}} return left;        }};

Written question 48. Leetcode OJ (35)

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.