Thursday, April 14, 2022

Leet Code 34. Find First and Last Position of Element in Sorted Array

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

Example 1:

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]


isme do binary search chalaenge:

1st leftmost me jaakr to get first position of element
    -> end = mid - 1;
2nd rightmost me jakr to get last position of element
    -> start = mid + 1;

                                                

                                                
package pep.Day63;

public class LeetCode_34_Find_First_and_LastPosition_of_Element_in_SortedArray {
public static void main(String[] args) {
int[] ans = searchRange(new int[]{5, 7, 7, 8, 8, 10}, 8);
for (int x : ans) {
System.out.print(x + " ");
}
}

public static int[] searchRange(int[] nums, int target) {
return new int[]{binarySearch(nums, target, true), binarySearch(nums, target, false)};
}

public static int binarySearch(int[] nums, int target, boolean left) {
int n = nums.length, start = 0, end = nums.length - 1, ans = -1;

while (start <= end) {
int mid = start + (end - start) / 2;

if (nums[mid] < target) {
start = mid + 1;
} else if (nums[mid] > target) {
end = mid - 1;
} else {
// jese hi start == end ho jae, ans ko mid ke equal kr denge
ans = mid;
// abhi aesa ho skta ki mere left ya right me same element exist krta ho
// left to favour krne ke lea, e = mid-1 kr denge
if (left)
end = mid - 1;
else
start = mid + 1;
}
}

return ans;
}


}




No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...