首页 > 编程语言 > 详细

【LeetCode-35】在已排序的数组中查找给出的目标值(包含目标值不存在的操作)

时间:2020-04-26 15:10:57      阅读:45      评论:0      收藏:0      [点我收藏+]
//My Method
    public static int searchInsert(int[] nums, int target) {
        int index = -1;
        for (int i=0; i<nums.length; i++)
            if (nums[i] == target)
                index = i;
        if (index == -1) {
            //位置可能是最左、最右或者中间
            //1、最左
            if (target < nums[0])
                return 0;
            //2、最右
            if (target > nums[nums.length-1])
                return nums.length;
            //3、中间
            int low = 0;
            int high = nums.length-1;
            while (low<=high) {
                int mid = (low+high)/2;
                if (target > nums[mid])
                    low = mid+1;
                if (target < nums[mid])
                    high = mid-1;
                // 1 4 7 9 11 15 17
            }
            System.out.println(low+"------"+high);
            return low;
        } else {
            return index;
        }
    }
    // Others‘ Method
    public static int searchInsert_others(int[] A, int target) {
        int low = 0, high = A.length-1;
        while(low<=high){
            int mid = (low+high)/2;
            if(A[mid] == target) return mid;
            else if(A[mid] > target) high = mid-1;
            else low = mid+1;
        }
        return low;
    }

 

【LeetCode-35】在已排序的数组中查找给出的目标值(包含目标值不存在的操作)

原文:https://www.cnblogs.com/nachdenken/p/12779445.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!