King_K

导航

【leetcode】Search Insert Position

题目是这样的:

  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

  对一个排序好的列表(假设里面没重复的数字),以及一个数字,如果这个数字在列表里,则返回下标,否则,返回这个数字插入的位置。

  思路很清晰很简单,折半就行了。重点是要考虑一些极限情况。我一般写代码的思路是先把大致框架写出来,然后完善极限情况。

  1.如果要插入的数字不大于第一个数,则插入位置0,即开始位置s.

  2..如果要插入的数字大于最后一个数,则插入最后一个位置之后,即e+1.

  3.如果要插入的数字等于最后一个数,则插入位置为列表最后一个,即终止位置e.

  4.如果要插入的数字在中间的话,则往起始位置后一位插,即s+1.

  最后运行时间是55,查看了人家15ms的代码。思想是一致的,但是差距就在于人家做了优化(对于少量数据来说应该算是优化了),不是折半来的,而是一个数字一个数字来的,只能说各取所长吧。

  代码如下:

class Solution:
    # @param A, a list of integers
    # @param target, an integer to be inserted
    # @return integer
    def searchInsert(self, A, target):
        Alen = len(A)
        s = 0
        e = Alen - 1
        m = e/2
        res = -1
        while(s < e and s < m and e > m):
            if A[m] == target:
                res = m
                break
            else:
                if A[m] < target:
                    s = m
                    m = (s + e)/2
                else:
                    e = m
                    m = (s + e)/2
        if res == -1:
            if target <= A[s]: #若出现插入的数字跟第一个数字一样,则在这个位置插入
                res = s
            elif target > A[e]: #若出现插入的数字比最后一个还大,则插入最后一个位置之后
                res = e + 1 
            else:   #如果在中间,则在其后面一个位置插入
                res = s + 1
        return res

  

posted on 2015-01-21 17:32  King_K  阅读(166)  评论(0编辑  收藏  举报