LeetCode solution report -- Search Insert Position

Source: Internet
Author: User

LeetCode solution report -- Search Insert Position

Question:

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
Click to solve the problem: Search Insert Position

Analysis: Find the subscript of the given target number from the given ordered array. If there is a subscript, return the subscript. If there is no subscript, return the subscript of the position where the target number should be inserted.
Two feasible ideas are provided:
1 ).Binary Search
A. The classic binary search problem exists.
B. if the condition does not exist, add the criterion nums [mid] <target & nums [mid + 1]> target because, if the target exists, the relationship between nums [mid] and target must have three types of ">", "<", and "= ".
2 ).Double pointer Method
The dual-pointer method has many judgment conditions. The basic principle is left, and the two-pointer method of rigoal points to the first and last elements of nums respectively, and starts to judge the elements from both sides (nums [left], nums [right]). if there is a target, the relationship between nums [left (right)] and target must have three types of ">", "<" and "= ". The index can be found based on this judgment criterion.

The brute force law can also be solved, but it will time out. I have never tried it. Although the question has no time complexity limit, it should not be allowed.
The idea of GTI is similar to that of Search for range. for details, refer to this blog.
The problem is changed to a problem with Two-Point lookup. The problem is solved by Two-Point lookup.

Java code Accepted:
Binary Search:

public class Solution {    public int searchInsert(int[] nums, int target) {        //Binary Search        int left = 0;        int right = nums.length - 1;        while(left <= right){            int middle = (left + right) / 2;            if(nums[middle] == target)                return middle;            else if(nums[middle] < target){                left = middle + 1;            }else if(nums[middle] > target){                right = middle - 1;            }else if(nums[middle] < target && nums[middle + 1] > target){                return middle;            }        }         return left;    }}

Double Points Search:

public class Solution {    public int searchInsert(int[] nums, int target) {        //double points search        int left = 0;        int right = nums.length - 1;        //flag for whether nums[left] > target or nums[right] < target        int flag = 0;        //save index of target        int index = 0;        while(left <= right){            //when nums's length == 1            if(left == right){                if(nums[left] > target)                    return left;                else if(nums[left] < target)                    return left + 1;                else                    return left;            }            //find target,then save left to index            else if(nums[left] == target){                index = left;                break;            }            //find target,then save right to index            else if(nums[right] == target){                index = right;                break;            }            //when nums[left] < target, if nums[left + 1] > target, target not exsist           else if(nums[left] < target){                left ++;                flag = 1;            }            else if(flag == 1 && nums[left] > target){                index = left;                break;            }            //when nums[right] > target, if nums[right - 1] < target, target not exsist            else if(nums[right] > target){                right --;                flag = 1;            }            else if(flag == 1 && nums[right] < target){                index = right;                break;            }        }        return index;    }}

Python code:
Binary Search:

class Solution(object):    def searchInsert(self, nums, target):        """        :type nums: List[int]        :type target: int        :rtype: int        """        left = 0        right = len(nums) - 1        while(left <= right):            mid = (left + right) / 2            if(nums[mid] == target):                return mid            elif(nums[mid] < target):                left = mid + 1            elif(nums[mid] > target):                right = mid - 1            elif(nums[mid] < target and nums[mid + 1] < target):                return mid + 1        return left

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.