-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday12.java
More file actions
110 lines (90 loc) · 2.38 KB
/
day12.java
File metadata and controls
110 lines (90 loc) · 2.38 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
//ques1:704. Binary Search
//link:https://leetcode.com/problems/binary-search/description/
class Solution {
public int search(int[] nums, int target) {
int low = 0, high = nums.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (target == nums[mid]) {
return mid;
} else if (target > nums[mid]) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
}
//TC: O(logN)
//SC: O(1)
//ques2:34. Find First and Last Position of Element in Sorted Array
//link:https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/description/
class Solution2 {
public int bn(int[] nums,int target,int is){
int low=0;
int high=nums.length-1;
int ans=-1;
while(low<=high){
int mid = low + (high - low) / 2;
if(target==nums[mid]){
ans=mid;
if(is==0){
high=mid-1;
}
else{
low=mid+1;
}
}
else if(target> nums[mid]){
low=mid+1;
}
else{
high=mid-1;
}
}
return ans;
}
public int[] searchRange(int[] nums, int target) {
int first=bn(nums,target,0);
int last=bn(nums,target,1);
return new int[]{first,last};
}
}
// TC: O(logN)
//SC: O(1)
//ques3:35.Search Insert Position
//link:https://leetcode.com/problems/search-insert-position/description/
class Solution3 {
public int bn(int[] nums,int target){
int low=0;
int high=nums.length-1;
int bound=-1;
int mid=0;
while(low<=high){
mid=low+(high-low)/2;
if(target==nums[mid]){
bound=mid;
break;
}
else if(target>nums[mid]){
low=mid+1;
}
else{
high=mid-1;
}
}
if(bound==-1){
if(nums[mid]>target)
return mid;
else
return mid+1;
}
return bound;
}
public int searchInsert(int[] nums, int target) {
return bn(nums,target);
}
}
//TC:O(logN)
//SC:O(1)