classSolution{ publicintchalkReplacer(int[] chalk, int k){ int n = chalk.length; long total = 0; for (int num : chalk) { total += num; } k %= total; int res = -1; for (int i = 0; i < n; ++i) { if (chalk[i] > k) { res = i; break; } k -= chalk[i]; } return res; } }
classSolution{ publicintchalkReplacer(int[] chalk, int k){ int n = chalk.length; if (chalk[0] > k) { return0; } for (int i = 1; i < n; ++i) { chalk[i] += chalk[i - 1]; if (chalk[i] > k) { return i; } }
k %= chalk[n - 1]; return binarySearch(chalk, k); }
publicintbinarySearch(int[] arr, int target){ int low = 0, high = arr.length - 1; while (low < high) { int mid = (high - low) / 2 + low; if (arr[mid] <= target) { low = mid + 1; } else { high = mid; } } return low; } }