LeetCode——Search for a Range

来源:互联网 发布:xrd图谱分析软件 编辑:程序博客网 时间:2024/05/16 19:19

Search for a Range

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].

没有用二分查找实现

Java代码:

public class Solution {    public int[] searchRange(int[] A, int target) {        int start =-1;        int end = -1;        int[] a = new int[2];        for(int i =0;i<A.length;i++)        {            if(A[i] ==target)            {                if(start == -1)start =i;                if(i!=A.length-1)                if(A[i+1] != target) {end = i;break;}            }        }        if(start !=-1&&end == -1)        end = A.length-1;                a[0] = start;        a[1]=end;        return a;            }}


0 0
原创粉丝点击