private static int[] candy(int[] ratings) { int[] candy = new int[ratings.length]; Arrays.fill(candy, 1); // increasing for (int i = 1; i < ratings.length; i++) { if (ratings[i] > ratings[i - 1]) { candy[i] = candy[i - 1] + 1; } } // decreasing for (int j = ratings.length - 2; j >= 0; j--) { if (ratings[j] > ratings[j + 1]) { if (((j - 1 >= 0)) && (ratings[j - 1] < ratings[j])) { candy[j] = Math.max(candy[j], candy[j - 1] + 1); } else { candy[j] = candy[j + 1] + 1; } } } // int sum = 0; // for(int k=0; k<candy.length; k++) sum+=candy[k]; return candy; }
public static int findSameMin(int[] A, int[] B) { Arrays.sort(A); Arrays.sort(B); int indexA = 0; int indexB = 0; while (indexA < A.length && indexB < B.length) { int headOfA = A[indexA]; int headOfB = B[indexB]; if (headOfA == headOfB) { return headOfA; } else if (headOfA < headOfB) { indexA++; } else { indexB++; } } return -1; }
private static List<List<Integer>> threeSum(int[] num) { List resultList = new ArrayList<ArrayList>(); Arrays.sort(num); int length = num.length; for (int i = 0; i < length - 2; ) { int j = i + 1, k = length - 1; while (j < k) { int sum = num[i] + num[j] + num[k]; if (sum == 0) { List<Integer> list = new ArrayList<Integer>(); list.add(num[i]); list.add(num[j]); list.add(num[k]); resultList.add(list); do { j++; } while (num[j] == num[j - 1]); do { k--; } while (num[k] == num[k + 1]); } else if (sum > 0) { do { k--; } while (num[k] == num[k + 1]); } else { do { j++; } while (num[j] == num[j - 1]); } } do { i++; } while (num[i] == num[i - 1]); } return resultList; }