ACM题库~

LeetCode 34. Search for a Range

2017-09-15  本文已影响10人  关玮琳linSir

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;
    }
上一篇下一篇

猜你喜欢

热点阅读