【LeetCode-面试算法经典-Java实现】【034-Search for a Range(搜索一个范围)】

【034-Search for a Range(搜索一个范围)】


【LeetCode-面试算法经典-Java实现】【所有题目目录索引】

原题

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

题目大意

  给定一个排好序的数组,同时给定一个要查找的值 ,找出这个数在数组中的出现在起始和结束位置。

   算法的时间复杂度要求为log(N)。

   如果没有找到就返回[-1, -1]

解题思路

  (假定数组是递增有序的)先用二分查找算法看数组中是否存在这个数,如果不存在就返回[-1,-1]

  如果存在就分别找这个数最后一次出来现的位置和最开始出现的位置。找最后出现的位置时,先从数组最后一个位置开始找,如果大于待找的值,就前近一个位置,还大于就前近2个,以2找指数数增加,如果小于就退回到原来位置的后一个进行查找,重新按1,2,4、、、这样子的方式进行,直到找到为止。对于找最先的元素也是一样的。

代码实现

算法实现类

public class Solution {
    public int[] searchRange(int[] A, int target) {

        if (A == null || A.length == 0) {
            return new int[]{-1, -1};
        }

        int lo = 0;
        int hi = A.length - 1;
        int mi = 0;
        // 查找数组中是否存在值为target的元素
        while (lo <= hi) {
            mi = lo + (hi - lo) / 2;
            if (target < A[mi]) {
                hi = mi - 1;
            } else if (target > A[mi]) {
                lo = mi + 1;
            } else {
                break;
            }

        }

        if (A[mi] != target) {
            return new int[]{-1, -1};
        }

        lo = searchFirst(A, 0, mi, target);
        hi = searchLast(A, mi, A.length - 1, target);

        return new int[]{lo, hi};
    }

    /**
     * 找target最先出现的位置,查找的范围是[lo, hi],A[hi]等于target,A为有序数组
     *
     * @param A      待查找的数组
     * @param lo     查找的起始位置
     * @param hi     查找的结束位置
     * @param target 查找的值
     * @return target最先出现的位置
     */
    private int searchFirst(int[] A, int lo, int hi, int target) {

        int gap = 1;
        do {
            hi -= gap;
            if (hi < lo || A[hi] != target) {
                hi += gap;

                if (hi <= lo || A[hi - 1] != target) {
                    return hi;
                } else {
                    gap = 1;
                    hi--;
                }
            } else {// 在上一次的位置后退gap个依然相等
                gap *= 2;
            }
        } while (true);

    }

    /**
     * 找target最后出现的位置,查找的范围是[lo, hi],A[lo]等于target,A为有序数组
     *
     * @param A      待查找的数组
     * @param lo     查找的起始位置
     * @param hi     查找的结束位置
     * @param target 查找的值
     * @return target最后出现的位置
     */
    private int searchLast(int[] A, int lo, int hi, int target) {
        int gap = 1;
        do {
            lo += gap;
            if (lo > hi || A[lo] != target) {
                lo -= gap;

                if (lo >= hi || A[lo + 1] != target) {
                    return lo;
                } else {
                    gap = 1;
                    lo++;
                }
            } else {// 在上一次的位置前进gap个依然相等
                gap *= 2;
            }
        } while (true);
    }
}

评测结果

  点击图片,鼠标不释放,拖动一段位置,释放后在新的窗口中查看完整图片。

特别说明

欢迎转载,转载请注明出处【http://blog.csdn.net/derrantcm/article/details/47079319

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

时间: 2024-10-21 21:15:57

【LeetCode-面试算法经典-Java实现】【034-Search for a Range(搜索一个范围)】的相关文章

[LeetCode] 34. Search for a Range 搜索一个范围(Find First and Last Position of Element in Sorted Array)

原题目:Search for a Range, 现在题目改为: 34. Find First and Last Position of Element in Sorted Array Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. Your algorithm's runtime complexity

88. Merge Sorted Array【leetcode】算法,java将两个有序数组合并到一个数组中

88. Merge Sorted Array Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note:You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The n

LeetCode第[79]题(Java):Word Search(矩阵单词搜索)

题目:矩阵单词搜索 难度:Medium 题目内容: Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same

[LeetCode] 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,

【LeetCode-面试算法经典-Java实现】【079-Word Search(单词搜索)】

[079-Word Search(单词搜索)] [LeetCode-面试算法经典-Java实现][所有题目目录索引] 原题 Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally

【LeetCode-面试算法经典-Java实现】【096-Unique Binary Search Trees(唯一二叉搜索树)】

[096-Unique Binary Search Trees(唯一二叉搜索树)] [LeetCode-面试算法经典-Java实现][所有题目目录索引] 原题 Given n, how many structurally unique BST's (binary search trees) that store values 1-n? For example, Given n = 3, there are a total of 5 unique BST's. 1 3 3 2 1 \ / / /

【LeetCode-面试算法经典-Java实现】【098-Validate Binary Search Tree(验证二叉搜索树)】

[098-Validate Binary Search Tree(验证二叉搜索树)] [LeetCode-面试算法经典-Java实现][所有题目目录索引] 原题 Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys le

【LeetCode-面试算法经典-Java实现】【109-Convert Sorted List to Binary Search Tree(排序链表转换成二叉排序树)】

[109-Convert Sorted List to Binary Search Tree(排序链表转换成二叉排序树)] [LeetCode-面试算法经典-Java实现][全部题目文件夹索引] 原题 Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. 题目大意 给定一个升序的单链表.将它转换成一颗高度平衡的二叉树 解题思路 解法

【LeetCode-面试算法经典-Java实现】【108-Convert Sorted Array to Binary Search Tree(排序数组转变为平衡二叉树)】

[108-Convert Sorted Array to Binary Search Tree(排序数组转变为平衡二叉树)] [LeetCode-面试算法经典-Java实现][所有题目目录索引] 原题 Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 题目大意 给定一个升序排列的二叉树,将其转换为一棵高度平衡的二叉树. 解题思路 采用递归分治法. 代码

【LeetCode-面试算法经典-Java实现】【033-Search in Rotated Sorted Array(在旋转数组中搜索)】

[033-Search in Rotated Sorted Array(在旋转数组中搜索)] [LeetCode-面试算法经典-Java实现][全部题目文件夹索引] 原题 Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search.