注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
Utilization Checks :
其中一个测试案例是:[46, 73, 77, 53, 75, 22, 55, 84, 45, 40, 80, 66, 54, 39, 68, 23, 54, 22, 11, 91, 47, 56, 91, 97, 5, 44, 62, 73, 26, 99, 96, 74, 4单的那些外,马上上到500个长度的startIndices,要确保你的代码是O(n+m)的复杂度。我考完后修改的代码:
- public static List<Integer> numberOfItems(String s, List<Integer> startIndices, List<Integer> endIndices) {
- List<Integer> result = new ArrayList<>();
-
- if (s == null || s.isEmpty()) {
- return result;
- }
-
- char[] charArray = s.toCharArray();
- List<Integer> pipePositions = new ArrayList<>();
- int[] nextIndexInPipePositions = new int[charArray.length]; //for each character in the string, the valid counting point will be from the position indicated by the index of pipePositions. for example, "**|**|" the pipePositions will be [2,5] and nextIndexInPipePositions will be [0,0,0,1,1,1] indicating [2,2,2,5,5,5]
- for (int i = 0; i < charArray.length; i++) {
- nextIndexInPipePositions[i] = pipePositions.size();
- if (charArray[i] == '|') {
- pipePositions.add(i);
- }
- }
-
- int indicesSize = Math.min(startIndices.size(), endIndices.size());
- for (int i = 0; i < indicesSize; i++) {
- int firstPipePositionIndex = nextIndexInPipePositions[startIndices.get(i) - 1];
- int lastPipePositionIndex = nextIndexInPipePositions[endIndices.get(i) - 1];
- if (charArray[endIndices.get(i) - 1] != '|') { //the next pipe is after the endIndex - should count to the previous pipe
- lastPipePositionIndex--;
- }
- if (lastPipePositionIndex > firstPipePositionIndex) {
- // count of *s = the total distance between the first pipe and the last pipe - the pipe count between the fist piple and the last pipe
- result.add(pipePositions.get(lastPipePositionIndex) - pipePositions.get(firstPipePositionIndex) - lastPipePositionIndex + firstPipePositionIndex);
- } else { // no pipe or only one pipe between
- result.add(0);
- }
- }
-
- return result;
- }
复制代码
|