Skip to content

Commit cf8dd0d

Browse files
committed
Added 2 solutions
1 parent 94b5a78 commit cf8dd0d

2 files changed

+86
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode(int x) { val = x; }
7+
* }
8+
*/
9+
class Solution {
10+
public int getDecimalValue(ListNode head) {
11+
int length = getLength(head);
12+
int sum = 0;
13+
while (head != null) {
14+
sum += ((int) Math.pow(2, length - 1)) * head.val;
15+
length--;
16+
head = head.next;
17+
}
18+
return sum;
19+
}
20+
21+
private int getLength(ListNode head) {
22+
int count = 0;
23+
while (head != null) {
24+
count++;
25+
head = head.next;
26+
}
27+
return count;
28+
}
29+
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
class Solution {
2+
public int findSpecialInteger(int[] arr) {
3+
int n = arr.length;
4+
int oneFourthNum = arr[n / 4];
5+
int halfNum = arr[n / 2];
6+
int threeFourthNum = arr[3 * n / 4];
7+
if(Math.max(n/4, binarySearchRight(arr, 0, n - 1, oneFourthNum)) -
8+
Math.min(n/4, binarySearchLeft(arr, 0, n - 1, oneFourthNum)) >= arr.length / 4) {
9+
return oneFourthNum;
10+
}
11+
if(Math.max(n/2, binarySearchRight(arr, 0, n - 1, halfNum)) -
12+
Math.min(n/2, binarySearchLeft(arr, 0, n - 1, halfNum)) >= arr.length / 4) {
13+
return halfNum;
14+
}
15+
if(Math.max((3 * n)/4, binarySearchRight(arr, 0, n - 1, threeFourthNum)) -
16+
Math.min((3 * n)/4, binarySearchLeft(arr, 0, n - 1, threeFourthNum)) >= arr.length / 4) {
17+
return threeFourthNum;
18+
}
19+
return -1;
20+
}
21+
22+
private int binarySearchLeft(int[] arr, int start, int end, int num) {
23+
int minIdx = Integer.MAX_VALUE;
24+
while (start < end) {
25+
int mid = (start + end) / 2;
26+
if (arr[mid] == num) {
27+
minIdx = Math.min(mid, minIdx);
28+
end = mid - 1;
29+
}
30+
else if (arr[mid] < num) {
31+
start = mid + 1;
32+
}
33+
else {
34+
end = mid - 1;
35+
}
36+
}
37+
return minIdx;
38+
}
39+
40+
private int binarySearchRight(int[] arr, int start, int end, int num) {
41+
int maxIdx = Integer.MIN_VALUE;
42+
while (start < end) {
43+
int mid = (start + end) / 2;
44+
if (arr[mid] == num) {
45+
maxIdx = Math.max(mid, maxIdx);
46+
start = mid + 1;
47+
}
48+
else if (arr[mid] < num) {
49+
start = mid + 1;
50+
}
51+
else {
52+
end = mid - 1;
53+
}
54+
}
55+
return maxIdx;
56+
}
57+
}

0 commit comments

Comments
 (0)