• [leetcode 34] search for a range


    1 题目:

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

    2 思路:

    好吧,刚开始看到这个题目,一想,不就是一个二分查找吗。然后再两边找相等的。

    结果提交呵呵了,运行时间只超过0.5%的人。

    看别人的代码,原来要两次二分搜索,一次找左边位置,一次要找右边位置。

    看懂了其中一个人的代码,主要是  searchFirstEqualOrGreater这个函数。调用两次就确定范围了。

    3 代码:

    public class Solution {
        public int[] searchRange(int[] nums, int target) {
            if(nums == null || nums.length == 0){
                return new int[] {-1,-1};
            }
            
            int[] result = new int[2];
            result[0] = findFirstEqualOrGreater(nums,target);
            if(result[0] == nums.length || nums[result[0]] != target){
                return new int[] {-1,-1};
            }
            
            result[1] = findFirstEqualOrGreater(nums,target+1)-1;
            return result;
        }
        
        private int findFirstEqualOrGreater(int[] nums,double target){
            int lo = 0;
            int hi = nums.length;
            int index = -1;
            while(lo < hi){
                index = lo + ((hi-lo)>>2);
                if (nums[index]<target){
                    lo = index+1;
                }else{
                    hi = index;
                }
            }
            return lo;
        }
    }
  • 相关阅读:
    捕捉整个桌面的图片
    在Image控件中绘制文字
    绘图
    Image1.Canvas画图笔刷
    将图片序列保存为GIF文件
    拷贝剪贴板图像到窗体
    显示 png 图片
    将图片以字符串方式保存
    复制图片的一部分
    反转字符串
  • 原文地址:https://www.cnblogs.com/lingtingvfengsheng/p/4842793.html
Copyright © 2020-2023  润新知