forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add java solution to lc problem: No.3048 (doocs#2387)
No.3048.Earliest Second to Mark Indices I Co-authored-by: Libin YANG <[email protected]>
- Loading branch information
Showing
3 changed files
with
135 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
45 changes: 45 additions & 0 deletions
45
solution/3000-3099/3048.Earliest Second to Mark Indices I/Solution.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
class Solution { | ||
public int earliestSecondToMarkIndices(int[] nums, int[] changeIndices) { | ||
int l = 0; | ||
int r = changeIndices.length + 1; | ||
while (l < r) { | ||
final int m = (l + r) / 2; | ||
if (canMark(nums, changeIndices, m)) { | ||
r = m; | ||
} else { | ||
l = m + 1; | ||
} | ||
} | ||
return l <= changeIndices.length ? l : -1; | ||
} | ||
|
||
private boolean canMark(int[] nums, int[] changeIndices, int second) { | ||
int numMarked = 0; | ||
int decrement = 0; | ||
// indexToLastSecond[i] := the last second to mark the index i | ||
int[] indexToLastSecond = new int[nums.length]; | ||
Arrays.fill(indexToLastSecond, -1); | ||
|
||
for (int i = 0; i < second; ++i) { | ||
indexToLastSecond[changeIndices[i] - 1] = i; | ||
} | ||
|
||
for (int i = 0; i < second; ++i) { | ||
// Convert to 0-indexed. | ||
final int index = changeIndices[i] - 1; | ||
if (i == indexToLastSecond[index]) { | ||
// Reach the last occurrence of the number. | ||
// So, the current second will be used to mark the index. | ||
if (nums[index] > decrement) { | ||
// The decrement is less than the number to be marked. | ||
return false; | ||
} | ||
decrement -= nums[index]; | ||
++numMarked; | ||
} else { | ||
++decrement; | ||
} | ||
} | ||
return numMarked == nums.length; | ||
} | ||
} |