Leetcode刷题day2

来源:互联网 发布:系统之家数据恢复 编辑:程序博客网 时间:2024/06/08 08:06

今天自己AC的一道题:

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

很简单就是分类讨论

第一种: 我自己的方法,麻烦,但是好理解的做法

public class Solution {    public int searchInsert(int[] nums, int target) {        int index=0;        for(int i=0;i<nums.length;i++)        {            if(nums[i]==target)            {                return i;            }            if(nums[i]<target)            {                if(i!=nums.length-1)                {                       index++;                       if(nums[i+1]>target)                       {                        return index;                        }                }                else                {                    return nums.length;//对应【1,3,5,6】,7-->4这种情况                                    }            }              if(nums[i]>target)            {                return index;               }                 }    return 9999; //这行必须return个int,否则报错,程序不能运行          }}

第二种:

看到一个优化很多的二分法解题方法,才8行!:

  public int searchInsert(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;    }

佩服这位大神对边界控制的精准,我确实想不出来他是怎么想出来的


第三种 依旧是二分法

public class Solution {public int searchInsert(int[] nums, int target) {    int low = 0, high = nums.length;    while(low < high) {        int mid = low + (high - low) / 2;//其实就是(low+high)/2        if(nums[mid] < target)            low = mid + 1;        else            high = mid;    }    return low;  }}


佩服这位大神对边界的精准控制,我确实想不出来它是怎么想出来的,但是它比第二种做法的好处我个人认为在于

1.统一返回值出口,更规范

2.把nums[mid]>=target的情况一并讨论了


第四种:

class Solution(object):    def searchInsert(self, nums, target):        """        :type nums: List[int]        :type target: int        :rtype: int        """               return len([x for x in nums if x<target])


利用了python里列表切片的功能,在算法上高明的地方是, x<target是截止条件,那么x+1>target或者 =target其实可以归并为一类,并不关心是否能取到等号。





原创粉丝点击