-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAlgoPlan0806
121 lines (109 loc) · 3.19 KB
/
AlgoPlan0806
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
111
112
113
114
115
116
117
118
119
120
121
#twin-paired linked list
##idea: store link node's info in an array for traversal
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public int pairSum(ListNode head) {
int n = 0;
ListNode p1 = head;
ListNode p2 = head;
while(p1!=null){
n++;
p1 = p1.next;
}
int[] ans = new int[n];
for (int j = 0;j < n;j++){
ans[j] = p2.val;
p2 = p2.next;
}
int sum = 0;
int cur =0;
for (int i =0; i < n/2;i++){
cur = ans[i] + ans[n-1-i];
if (cur > sum) sum = cur;
}
return sum;
}
}
#longest mountain in an array
#key idea:
-loop over left side and right side
-take care of the pleateau
-get the answer of each right side
class Solution {
public int longestMountain(int[] arr) {
int count = 0;
int max = 0;
int n = arr.length;
int left = 0;
int right = 0;
while (left < n){
while (left < n-1 && arr[left] >= arr[left+1]){
left++;
}
//at one possible left point
right = left +1;
//if it is a high pleateau
while (right < n-1 && arr[right] < arr[right+1]){
right++;
}
while (right < n-1 && arr[right] > arr[right+1]){
right++;
//it is within the right side loop
//because if it just keeps increasing
//it cannot be detected
if (right-left+1 >=3 && right-left +1 > max) max = right-left+1;
}
left = right;
}
return max ;
}
}
#find num of pairs to get a certain sum
key idea:
use a hashmap to fasten the process
class FindSumPairs {
int[] nums1 = null;
int[] nums2 = null;
Map<Integer,Integer> map1 = new HashMap();
Map<Integer,Integer> map2 = new HashMap();
public FindSumPairs(int[] nums1, int[] nums2) {
this.nums1 = nums1;
this.nums2 = nums2;
for (int i = 0; i< nums1.length;i++){
map1.put(nums1[i],map1.getOrDefault(nums1[i],0)+1);
}
for (int j = 0; j < nums2.length;j++){
map2.put(nums2[j],map2.getOrDefault(nums2[j],0)+1);
}
}
public void add(int index, int val) {
map2.put(nums2[index],map2.get(nums2[index])-1);
nums2[index] +=val;
map2.put(nums2[index],map2.getOrDefault(nums2[index],0)+1);
}
public int count(int tot) {
int counting = 0;
for (int k : map1.keySet()){
int rest = tot-k;
if (map2.containsKey(rest)){
counting +=map2.get(rest)*map1.get(k);
}
}
return counting;
}
}
/**
* Your FindSumPairs object will be instantiated and called as such:
* FindSumPairs obj = new FindSumPairs(nums1, nums2);
* obj.add(index,val);
* int param_2 = obj.count(tot);
*/