publicclassSolution{publicintjump(int[] nums){int jumps =0;int maxReach =0;int currentReach =0;for(int i =0; i < nums.length -1; i++){maxReach =Math.max(maxReach, i + nums[i]);if(i == currentReach){jumps++;currentReach = maxReach;if(currentReach >= nums.length -1)break;}}return jumps;}}
复杂度分析:
时间复杂度: O(n),其中 n 是数组的长度。我们只需遍历数组一次。
空间复杂度: O(1),只使用了常数级别的额外空间。
解题思路:
初始化变量:
result:记录结果。
last:记录当前字符最后一次出现的索引位置。
start:当前段的开始位置。
end:当前段的结束位置。
遍历数组:
更新当前段的结束位置为当前字符最后一次出现的索引位置。
如果当前的遍历位置 i == 当前段的结束位置,向结果集添加字符串的片段长度 end - start + 1,并更新当前段的开始位置。
返回结果: 返回 result。
Java代码:
classSolution{publicList<Integer>partitionLabels(String s){List<Integer> result =newList<>();int[] last =newint[26];for(int i =0; i < s.length(); i++)last[s.charAt(i)-'a']= i;int start =0, end =0;for(int i =0; i < s.length(); i++){end =Math.max(end, last[s.charAt(i)-'a']);if(i == end){result.add(end - start +1);start = end +1;}}return result;}}