-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay12.java
More file actions
86 lines (75 loc) · 2.13 KB
/
Copy pathDay12.java
File metadata and controls
86 lines (75 loc) · 2.13 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
//Problem 1:Binary Search
//https://leetcode.com/problems/binary-search/description/
class Solution {
public int search(int[] nums, int target) {
int start=0,end=nums.length-1;
while(start<=end){
int mid=(start+end)/2;
if(nums[mid]==target)
return mid;
else if(nums[mid]>target)
end=mid-1;
else
start=mid+1;
}
return -1;
}
}
//TC:O(logn)
//SC:O(1)
//Problem 2:https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/description/
class Solution {
public int[] searchRange(int[] nums, int target) {
int left = Left(nums, target);
int right = Right(nums, target);
return new int[] { left, right };
}
public int Left(int[] nums, int target) {
int index = -1, low = 0, high = nums.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (nums[mid] == target) {
index = mid;
high = mid - 1;
} else if (nums[mid] < target)
low = mid + 1;
else
high = mid - 1;
}
return index;
}
public int Right(int[] nums, int target) {
int index = -1, low = 0, high = nums.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (nums[mid] == target) {
index = mid;
low = mid + 1;
} else if (nums[mid] < target)
low = mid + 1;
else
high = mid - 1;
}
return index;
}
}
//TC:O(logn)
//SC:O(1)
//Problem:https://leetcode.com/problems/search-insert-position/description/
class Solution {
public int searchInsert(int[] nums, int target) {
int start=0,end=nums.length-1;
while(start<=end){
int mid=(start+end)/2;
if(nums[mid]==target)
return mid;
else if(nums[mid]>target)
end=mid-1;
else
start=mid+1;
}
return start;
}
}
//TC:O(logn)
//SC:O(1)