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

LeetCode Search for a Range

时间:2014-11-02 12:11:14      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   os   ar   for   sp   div   

Given a sorted array of integers, find the starting and ending position of a given target value.

Your algorithm‘s runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

二分法查找,虽然AC了,但写的不太好。

public class Solution {
    ArrayList<Integer> arrayList=new ArrayList<>();
    int[] res=new int[]{-1,-1};
    public int[] searchRange(int[] A, int target) {
        if (A.length==0) {
            return null;
        }
        int middle = (A.length-1)/2;
        int end=A.length-1;
        if (A[middle]>target) {
            search(A, 0, middle, target);
        }else if (A[middle]<target) {
            search(A, middle, end, target);
        } else {
            search(A, 0, middle, target);
            search(A, middle+1, end, target);
        }
        
        if (arrayList.isEmpty()) {
            return res;
        }else {
            res[0]=arrayList.get(0);
            res[1]=arrayList.get(arrayList.size()-1);
            return res;
        }
    }
    
    private void search(int[] A,int begin,int end,int target) {
        if(begin>end){
            return;
        }
        if (begin==end) {
            if (A[begin]==target) {
                if (!arrayList.contains(begin)) {
                    arrayList.add(begin);
                }
                            
            }
            return;
        }
    int middle = (begin+end)/2;
    if (A[middle]>target) {
        search(A, begin, middle, target);
        return;
    }
    if (A[middle]<target) {
        search(A, middle+1, end, target);
        return;
    }
    if (A[middle]==target) {
        search(A, begin, middle, target);
        search(A, middle+1, end, target);
        return;
    }
    
}

}

 

LeetCode Search for a Range

标签:style   blog   io   color   os   ar   for   sp   div   

原文地址:http://www.cnblogs.com/birdhack/p/4068913.html

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