码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Search Insert Position

时间:2015-04-04 12:20:44      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:leetcode

题意: 给出一个target找出他在有序数组中的位置
思路1: 直接遍历 复杂度O(N)
代码1:
    public int searchInsert1(int[] A, int target) {//直接遍历 算法O(N)
        int i = 0;
        if(target < A[0]) return 0;
        if(target > A[A.length - 1]) return A.length;
        for(; i < A.length; ++ i){
            if(A[i] == target) return i;
            if(target < A[i+1] && target > A[i]) return i + 1;
        }
        return i;
    }

思路2: 二分法,注意处理边界问题,算法复杂度 O(log(N))
代码2:

    public int searchInsert(int[] A, int target) {//二分法 算法O(log(N))
        int i = 0;

        if(target <= A[0]) return 0;
        if(target > A[A.length - 1]) return A.length;
        if(target == A[A.length - 1]) return A.length - 1;

        int start = 0, end = A.length - 1, mid;

        while (start < end){
            mid = start + (end - start) / 2;
            if(A[mid] < target){
                start = mid + 1;
            }else if(A[mid] > target){
                end = mid -1;
            }else {
                return mid;
            }
        }

        if(start >= end){
            if(target > A[end]) {
                return end + 1;
            }
            else if(target == A[end]) return end;
            else {
                return end;
            }
        }

        return i;
    }


[LeetCode] Search Insert Position

标签:leetcode

原文地址:http://blog.csdn.net/youmengjiuzhuiba/article/details/44871469

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!