leetcode 35

搜索插入位置

Posted by Static on July 17, 2020

题目链接:https://leetcode-cn.com/problems/search-insert-position/

题目描述


分析

1. 遍历

2. 二分法


代码实现

public enum Q35 {
    instance;

    public int searchInsert(int[] nums, int target) {
        if(nums[0]>=target){
            return 0;
        }
        if(nums[nums.length-1]<target){
            return nums.length;
        }
        if(nums[nums.length-1]==target){
            return nums.length-1;
        }
        for(int i=0;i<nums.length-1;i++){
            if(target==nums[i]){
                return i;
            }
            if(nums[i]<target&&nums[i+1]>target){
                return i+1;
            }
        }
        return -1;
    }

    // 二分法
    public int searchInsert1(int[] nums, int target) {
        if(nums[0]>target){
            return 0;
        }
        if(nums[nums.length-1]<target){
            return nums.length;
        }

        int l=0,r=nums.length-1;
        while (l<=r){
            int mid=(l+r)/2;
            if(nums[mid]==target){
                return mid;
            }else if(nums[mid]>target&&nums[mid-1]<target){
                return mid;
            }else if(nums[mid]<target&&nums[mid+1]>target){
                return mid+1;
            }else if(nums[mid]<target){
                l=mid+1;
            }else if(nums[mid]>target){
                r=mid-1;
            }

        }
        return -1;
    }

    public static void main(String[] args) {
        // assert 2
        System.out.println(Q35.instance.searchInsert(new int[]{1,3,5,6},5));
        System.out.println(Q35.instance.searchInsert1(new int[]{1,3,5,6},5));

        // assert 1
        System.out.println(Q35.instance.searchInsert(new int[]{1,3,5,6},2));
        System.out.println(Q35.instance.searchInsert1(new int[]{1,3,5,6},2));

        // assert 4
        System.out.println(Q35.instance.searchInsert(new int[]{1,3,5,6},7));
        System.out.println(Q35.instance.searchInsert1(new int[]{1,3,5,6},7));

        // assert 0
        System.out.println(Q35.instance.searchInsert(new int[]{1,3,5,6},0));
        System.out.println(Q35.instance.searchInsert1(new int[]{1,3,5,6},0));

        // assert 1
        System.out.println(Q35.instance.searchInsert1(new int[]{1,3},2));
        // assert 2
        System.out.println(Q35.instance.searchInsert1(new int[]{1,3},3));

        // assert 0
        System.out.println(Q35.instance.searchInsert1(new int[]{1},1));

    }
}

All over the place was six pence, but he looked up at the moon.

满地都是六便士,他却抬头看见了月亮。