Home [Binary Search] Find First and Last Position of Element in Sorted Array
Post
Cancel

[Binary Search] Find First and Last Position of Element in Sorted Array

‘Find First and Last Position of Element in Sorted Array’ in LeetCode (Medium)


📌 Problem

https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/

📌 Answer

The point

  • binary search : time complextiy is O(logN)

Result

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class Solution {
    public int[] searchRange(int[] nums, int target) {
        int[] result = new int[2];
        result[0] = findFirst(nums, target);
        result[1] = findLast(nums, target);
        return result;
    }

    private int findFirst(int[] nums, int target) {
        
        int idx = -1;
        int start = 0;
        int end = nums.length - 1;
        
        while (start <= end) {
            
            int mid = (start + end) / 2;
            
            // here is difference
            if (nums[mid] >= target)
                end = mid - 1;
            else
                start = mid + 1;
            
            if (nums[mid] == target) idx = mid;
        }
        return idx;
    }

    private int findLast(int[] nums, int target) {
        
        int idx = -1;
        int start = 0;
        int end = nums.length - 1;
        
        while (start <= end) {
            
            int mid = (start + end) / 2;
            
            // here is difference
            if (nums[mid] <= target)
                start = mid + 1;
            else
                end = mid - 1;
            
            if (nums[mid] == target) idx = mid;
        }
        return idx;
    }
}
/**
[Question]
- Find First and Last Position of Element in Sorted Array
- find the starting and ending position of a given target value.
- If target is not found in the array, return [-1, -1].

[Condition]
- 0 <= nums.length <= 10.5
- 10.9 <= nums[i] <= 10.9
- -10.9 <= target <= 10.9
**/

The source : https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/discuss/14734/Easy-java-O(logn)-solution

This post is licensed under CC BY 4.0 by the author.

[Algorithm] Generate Parentheses

[Algorithm] Binary search

Comments powered by Disqus.