美文网首页ACM题库~
LeetCode 34. Search for a Range

LeetCode 34. Search for a Range

作者: 关玮琳linSir | 来源:发表于2017-09-15 11:31 被阅读10次

Given an array of integers sorted in ascending order, 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 int[] searchRange(int[] nums, int target) {
        int[] result = { -1, -1 };
        if (nums.length == 0 || nums == null)
            return result;
        List<Integer> list = new ArrayList<Integer>();
        for (int i = 0; i < nums.length; i++)
            if (nums[i] == target)
                list.add(i);
        if (list.size() == 0)
            return result;
        result[0] = list.get(0);
        result[1] = list.get(list.size() - 1);
        return result;
    }

相关文章

网友评论

    本文标题:LeetCode 34. Search for a Range

    本文链接:https://www.haomeiwen.com/subject/xtsssxtx.html