[Leetcode] 034. Search for a Range (Medium) (C++/java)

Source: Internet
Author: User

Index: [Leetcode] leetcode key index (C++/JAVA/PYTHON/SQL)
Github:https://github.com/illuz/leetcode

035. Search for a Range (Medium)
links

Title: https://leetcode.com/problems/search-for-a-range/
Code (GitHub): Https://github.com/illuz/leetcode

Test Instructions

Finds a range of numbers in an ordered array. (because the number is duplicated)

Analysis

Or two-point search variants.

    1. (c + +) directly with C + + STL lower_bound and upper_bound lazy.
    2. (Java) just change it directly from the ordinary two points.
Code

C++:

Class solution {public:vector<int> Searchrange (int a[], int n, int target) {int* lower = Lower_bound (A, a + N, targe t); int* upper = Upper_bound (A, a + N, target); if (*lower! = target) return vector<int> {-1, -1};elsereturn vector< Int>{lower-a, upper-a-1};};


Java:

public class Solution {public    int[] Searchrange (int[] A, int target) {        int[] ret = new int[2];        Ret[0] = ret[1] =-1;        int left = 0, right = a.length-1, mid;        while (left <= right) {            if (a[left] = = Target && A[right] = = target) {                ret[0] = left;                RET[1] = right;                break;            }            Mid = (right + left)/2;            if (A[mid] < target) {left                = mid + 1,            } else if (A[mid] > target) {right                = mid-1;            } else {
   if (a[right] = = target) {                    ++left;                } else {                    --right;}}        }        return ret;    }}


[Leetcode] 034. Search for a Range (Medium) (C++/java)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.