Leetcode刷题day2

今天自己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其实可以归并为一类,并不关心是否能取到等号。





  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值