lintcode(61)搜索区间

来源:互联网 发布:2016中小企业数据统计 编辑:程序博客网 时间:2024/06/06 02:48

描述:

给定一个包含 n 个整数的排序数组,找出给定目标值 target 的起始和结束位置。

如果目标值不在数组中,则返回[-1, -1]


样例:

给出[5, 7, 7, 8, 8, 10]和目标值target=8,

返回[3, 4]

public class Solution {    /**      *@param A : an integer sorted array     *@param target :  an integer to be inserted     *return : a list of length 2, [index1, index2]     */    public int[] searchRange(int[] A, int target) {        // write your code here        boolean find = false;        int[] result = {-1 , -1};                if(A == null || A.length == 0 ||target  < A[0] || target > A[A.length - 1]){            return result;        }        for(int i = 0;i<A.length;i++){            if(A[i] == target && !find){                result[0] = i;                find = true;            }            if(A[i] == target && find){                result[1] = i;            }        }                return result;    }}


0 0
原创粉丝点击