GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Add java solution for 34 (#65) · iamsathish/leetcode@354044a

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • java
    • 034_Find_First_and_Last_Position_of_Element_in_Sorted_Array.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎java/034_Find_First_and_Last_Position_of_Element_in_Sorted_Array.java‎

Copy file name to clipboard
+59Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
class Solution {
2+
/*
3+
Rule 1
4+
- Given array is sorted in non-decreasing order
5+
6+
Rule 2
7+
- Limit time complexity O(log n).
8+
9+
So I can use Binary Search Algorithm.
10+
*/
11+
public int[] searchRange(int[] nums, int target) {
12+
// initialize arr[0] -> maximum integer, arr[1] -> minimum integer
13+
int[] arr = {100001, -10};
14+
int s = 0;
15+
int e = nums.length - 1;
16+
17+
// find minimum index in nums with Binary Search alogorithm
18+
while (s <= e) {
19+
20+
int mid = (s + e) / 2;
21+
22+
if(nums[mid] > target) {
23+
e = mid - 1;
24+
}
25+
else if(nums[mid] <= target) {
26+
if(nums[mid] == target) {
27+
arr[0] = Math.min(arr[0], mid);
28+
arr[1] = Math.max(arr[1], mid);
29+
}
30+
s = mid + 1;
31+
}
32+
}
33+
34+
s = 0;
35+
e = nums.length - 1;
36+
37+
// find maximum index in nums with Binary Search alogorithm
38+
while(s <= e) {
39+
int mid = (s + e) / 2;
40+
41+
if(nums[mid] >= target) {
42+
if(nums[mid] == target) {
43+
arr[0] = Math.min(arr[0], mid);
44+
arr[1] = Math.max(arr[1], mid);
45+
}
46+
e = mid - 1;
47+
}
48+
else if(nums[mid] < target) {
49+
s = mid + 1;
50+
}
51+
}
52+
53+
// if arr data is initial data, set -1.
54+
if(arr[0] == 100001) arr[0] = -1;
55+
if(arr[1] == -10) arr[1] = -1;
56+
57+
return arr;
58+
}
59+
}

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.