码疯窝

LeetCode 每日一题 — Search Insert Position

2015/01/16 09:48:27    分类: 日志连载    0人评论 次浏览

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

算法分析: 这道题目异常的简单, 一度以为自己理解错了题意, 提前代码之后才了解, 然后题意就是这么简单.

Java:

public class Solution {
    public int searchInsert(int[] A, int target) {
        int l = A.length;
        int i = 0;
        for (; i <= l; i++) {
            if (i == l || target <= A[i])
                break;
        }
        return i;
    }
}

C++:

class Solution {
public:
    int searchInsert(int A[], int n, int target) {
        int i = 0;
        for (; i <= n; i++) {
            if (i == n || target <= A[i])
                break;
        }
        return i;
    }
};

Python:

class Solution:
    # @param A, a list of integers
    # @param target, an integer to be inserted
    # @return integer
    def searchInsert(self, A, target):
        l = len(A)
        for i in range(l + 1):
            if (l == i or target <= A[i]):
                break
        return i
继续查看有关 日志连载的文章

0个访客评论