leetcode204计数质数
class Solution {
public int countPrimes(int n) {
if (n < 3) return 0;
if (n == 3) return 1;
int count = 0;
boolean[] is = new boolean[n];
for (int i = 2; i < n; i++) {
if (!is[i]) {
count++;
for (int j = i + i; j < n; j += i) is[j] = true;
}
}
return count;
}
}
leetcode845数组中的最长山脉
class Solution {
public int longestMountain(int[] arr) {
int N = arr.length;
int res = 0;
for (int mid = 1; mid < N - 1; mid++) {
int left = mid - 1, right = mid + 1;
if (arr[left] >= arr[mid] || arr[right] >= arr[mid]) continue;
while (left > 0 && arr[left - 1] < arr[left]) left--;
while (right < N - 1 && arr[right + 1] < arr[right]) right++;
res = Math.max(res, right - left + 1);
}
return res;
}
}
leetcode829连续整数求和
class Solution {
public int consecutiveNumbersSum(int n) {
int res = 0, i = 1;
while (n > 0) {
if (n % i == 0) res++;
n -= i++;
}
return res;
}
}
leetcode949给定数字能组成的最大时间
class Solution {
public String largestTimeFromDigits(int[] arr) {
Arrays.sort(arr);
for (int i = 3; i >= 0; i--) {
if (arr[i] > 2) continue;
for (int j = 3; j >= 0; j--) {
if (i == j || arr[i] == 2 && arr[j] >= 4) continue;
for (int k = 3; k >= 0; k--) {
if (j == k || i == k || arr[k] >= 6) continue;
return "" + arr[i] + arr[j] + ":" + arr[k] + arr[6 - i - j - k];
}
}
}
return "";
}
}
|