zoukankan      html  css  js  c++  java
  • Java [leetcode 34]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].

    结题思路:

    采用二分法查找,如果找到再从这个位置向两边扩散,直到到达目标值的两边边界。

    代码如下:

    public class Solution {
        public int[] searchRange(int[] nums, int target) {
    		int[] result = { -1, -1 };
    		int left = 0;
    		int right = nums.length - 1;
    		int mid, low, high;
    
    		if (target > nums[right] || target < nums[left])
    			return result;
    
    		while (left <= right) {
    			mid = (left + right) / 2;
    			if (nums[mid] == target) {
    				low = mid;
    				high = mid;
    				while (low >= 0 && nums[low] == target)
    					low--;
    				result[0] = low + 1;
    				while (high < nums.length && nums[high] == target)
    					high++;
    				result[1] = high - 1;
    return result; } else if (nums[mid] > target) { right = mid - 1; } else { left = mid + 1; } } return result; } }
  • 相关阅读:
    Redis概述与安装
    CentOS-Linux系统下安装MySQL
    CentOS-Linux系统下安装Tomcat
    CentOS-Linux系统下安装JDK
    占位符
    设计模式之装饰者模式
    Servlet3.0
    注解入门
    PHP如何实现99乘法表?
    2017年PHP程序员未来路在何方?(转载)
  • 原文地址:https://www.cnblogs.com/zihaowang/p/4960203.html
Copyright © 2011-2022 走看看