leetcode Search Insert Position

265 篇文章 1 订阅
231 篇文章 0 订阅

 

Search Insert Position

 Total Accepted: 4060 Total Submissions: 12013My Submissions

 

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

 

Recommedation, STL implement, use first and length to binary search:

class Solution:
    def searchInsert(self, nums, target):
        #search lower bound 刚好是第一个插入的位置!!!
        first,cur_len = 0,len(nums)
        while (cur_len > 0):
            half = cur_len >> 1
            if (nums[first+half] < target):
                first = first+half+1
                cur_len = cur_len-(half+1)
            else: #这个因为是nums[first+half] 肯定>= target,所以只保留nums[0..first+half-1],如果上一个if里的元素都比target小,只能插在末尾
                cur_len = half
        return first

    def searchUpperBound(self, nums, target):
        # search upper bound 刚好是最后一个插入的位置!!!
        first,cur_len = 0,len(nums)
        while (cur_len > 0):
            half = cur_len >> 1
            if (nums[first+half] <= target):
                first = first+half+1
                cur_len = cur_len-(half+1)
            else: #这个因为是nums[first+half] 肯定> target,所以只保留nums[0..first+half-1],如果上一个if里的元素都小于等于target,只能插在末尾
                cur_len = half
        return first


s = Solution()
y = s.searchInsert([1,3,5,6],2)
print(y)

 

If dropping the left part will break the loop, mid + 1 is the answer;

If dropping the right part will break the loop, mid is the answer;

The AC code is ,but it's bad code format

 

class Solution {
 public:
  int searchInsert(int A[], int n, int target) {
    int l = 0, r = n - 1, mid;
    while (l <= r) {
      mid = (l + r) / 2;
      if (A[mid] == target)
        return mid;
      else if (A[mid] > target) {
        if (mid - 1 >= l)
          r = mid - 1;
        else
          return mid;
      }
      else if (A[mid] < target) {
        if (mid + 1 <= r)
          l = mid + 1;
        else
          return mid + 1;
      }
    }
    return mid;
  }
};

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值