Search for a range

原创 2015年07月07日 13:44:31
public class Solution {
    public int[] searchRange(int[] nums, int target) {
        int[] result = new int[2];
        result[0] = -1;
        result[1] = -1;
        if (nums == null || nums.length < 1) {
            return result;
        }
        int left = 0;
        int right = 0;
        //search for left bound.
        right = nums.length - 1;
        while (left + 1 < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] >= target) {
                right = mid;
            } else {
                left = mid;
            }
        }
        if (nums[left] == target) {
            result[0] = left;
        } else if (nums[right] == target) {
            result[0] = right;
        } else {
            result[0] = -1;
            result[1] = -1;
            return result;
        }
        //search for right bound.
        left = result[0];
        right = nums.length - 1;
        while (left + 1 < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] > target) {
                right = mid;
            } else {
                left = mid;
            }
        }
        if (nums[right] == target) {
            result[1] = right;
        } else {
            result[1] = left;
        }
        return result;
    }
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

leetcode(34). Search for a Range

problem Given an array of integers sorted in ascending order, find the starting and ending posi...

LeetCode Search for a Range

题目: Given a sorted array of integers, find the starting and ending position of a given target v...

LeetCode[Array]: Search for a Range

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

[LeetCode][Java] Search for a Range

题目: Given a sorted array of integers, find the starting and ending position of a given target v...

LeetCode OJ-34.Search for a Range

LeetCode OJ-34.Search for a Range题目描述 Given an array of integers sorted in ascending order, find t...

Leetcode || Search for a Range

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

leetcode 34. Search for a Range

import java.util.Stack; //Given a sorted array of integers, find the starting and ending position o...

LeetCode Search for a Range搜索特定数值的范围 三种方法求解

在排序数组中搜索一个值有多少个,并返回其两边下标,没有找到就返回[-1,-1]。注意时间效率是O(logN)。这就肯定要用到二分法的思想了。 主要难度是处理好下标的走势。 有三种方法可以求解: ...

LeetCode--Search for a range

DisciptionGiven an array of integers sorted in ascending order, find the starting and ending positio...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)