LeetCode brush title notes 35th title

Subject description:

Given a sorted array and a target, find the object in the array, and returns its index. If the target is not present in the array, it will be returned in sequence inserted position.

You may assume that no duplicate elements in the array.

Problem-solving ideas:

The idea is to use the most direct binary search, if ordered array contains elements equal to the target value, corresponding to the value of the index returned directly; if not then look after, return value corresponding cursor left. Another solution is to directly traverse the ordered array, conditions for traversing the array is smaller than the current access target value while traversing the cursor is less than the length of the array, the end of the traverse, the corresponding value is supposed to traverse the cursor value returned.

The first solution: binary search

Time complexity is: O (logn)

I saw the debate in the comments on the calculation of mid values, some say direct mid = (left + right) / 2 is unsafe, may overflow, so the wording is a more secure mid = left + (right - left ) / 2; like will overflow more than 10, there are two values, a 6, a 8, if computed directly, the 6 + 8 = 14> 10, overflow will occur, but by mid = left + (right - left) / 2 formula for calculating mid = 6 + (8-6) / 2, to avoid this problem, quite reasonable, it draws.

public int searchInsert(int[] nums, int target) {
        if (nums.length == 0 || (target < nums[0]))
            return 0;
        if (target > nums[nums.length-1])
            return nums.length;
        if (nums.length == 1){
            if (target>nums[0])
                return 1;
            else
                return 0;
        }
        int left = 0;
        int right = nums.length - 1;
        int mid = (left + right) / 2;
        while (left <= right){
            if (nums[mid] == target)
                return mid;
            else if (nums[mid] > target){
                right = mid - 1;
            }else {
                left = mid + 1;
            }
            mid = (right + left) / 2;
        }
        return mid + 1;
    }

The first solution continued: binary search to improve and reduce the number of cycles

This is the solution I see someone in the comments provided by the solution of the problem, the idea can learn, although I do not run fast speed, ha ha ha ha

    public int searchInsert3(int[] nums,int target){
        int lo=0,hi=nums.length;
        while(lo<hi-1){
            int mid=(lo+hi)>>1;
            if(target<nums[mid])
                hi=mid;
            else
                lo=mid;
        }
        return target<=nums[lo]? lo:++lo;
    }

The second solution: violence traversal

Super-short, time complexity is O (n)

    public int searchInsert2(int[] nums, int target) {
        int i;
        for(i=0;i<nums.length&&nums[i]<target;i++);
        return i;
    }

 

Guess you like

Origin www.cnblogs.com/yxym2016/p/12528331.html