【LeetCode35】【Search Insert Position】二分法查找

来源:互联网 发布:做汉化的软件 编辑:程序博客网 时间:2024/05/23 00:16

1. 题目原文

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would 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

2. 题目翻译

又是一个处理排好序的数组问题。写的方法应该返回target在数组中的位置,如果target不在数组中,返回target应该插入数组的哪个位置。

3. 题目分析

这道题用平常的解法解答十分简单,只要在循环数组每一个数的时候,返回第一次大于或者等于target的位置索引。

但是写这篇博文的主要原因并不是这道题,而是我意外发现在Submission Details中点击Accepted Solutions Runtime Distribution表格中的柱形时,是可以看到每一个时间维度里的示例代码。
我点击排名最靠前的柱形,看了“大神”的代码,获得了一个解题的新的方法–二分法查找,之前学习数据结构的时候学过,但是现在似乎忘得精光了,赶紧膜拜学习,自己写了实现代码。

4. java代码

(1)实现代码1(普通思路):

public int searchInsert1(int[] nums, int target) {        int i = 0;        while(i<nums.length){            if(nums[i]>=target){break;}            i++;        }        return i;    }

(2)实现代码2(二分法查找):

public int searchInsert2(int[] nums, int target) {        if(nums.length==0){return 0;}        int begin = 0,end = nums.length-1;        while(begin<=end){            int middle = (begin + end)/2;            if(nums[middle]==target){return middle;}            else if(nums[middle]>target){                end = middle - 1;            }else{                begin = middle + 1;            }        }        return begin;    }

5. 总结

这道题目的数据量比较小,所以二分法查找的效率并没有十分体现出来。但在数组长度比较长的的情况下,这种方法应该是一个更好的解题思路。
今后遇到数据量比较大,且是排好序数据的情况下,可以多尝试该方法,达到熟练应用的目的,与大家共勉。

0 0
原创粉丝点击