C_01 较大分组的位置
方法一:双指针
l 和 r 都指向相同的字符我们让 r++,l r 指向不同的字符时,我们检查 r-l 的值是否 >= 3。
- 注:有一种极端情况 [a,a,a],最后 r = 3, l = 0 时循环终止了,最后捕捉不了这种状态。
public List<List<Integer>> largeGroupPositions(String S) {
List<List<Integer>> group = new LinkedList<>();
char[] s = S.toCharArray();
int N = s.length;
int l = 0, r = l;
while (r < N) {
if (s[l] == s[r]) {
r++;
} else {
if (r - l >= 3) {
List<Integer> item = new LinkedList<>();
item.add(l);
item.add(r-1);
group.add(item);
}
l = r;
}
}
if (r - l >= 3) {
List<Integer> item = new LinkedList<>();
item.add(l);
item.add(r-1);
group.add(item);
}
return group;
}
复杂度分析
- 时间复杂度: ,
- 空间复杂度: ,
B_02
方法一:
复杂度分析
- 时间复杂度: ,
- 空间复杂度: ,
B_03 连续整数求和
方法一:枚举区间和(超时)
定义一个有 l 和 r 组成的窗口,然后我们让我对每一状态的窗口的累加和进行枚举,如果窗口的最后的值等于 n,证明这个窗口是可以作为答案的。
public int consecutiveNumbersSum(int N) {
int cnt = 0;
for (int r = 1; r <= N; r++) {
int n = N, l = r;
while (n > 0) {
n -= l;
l++;
}
if (n == 0)
cnt++;
}
return cnt;
}
复杂度分析
- 时间复杂度:
- 空间复杂度: ,
方法二:找规律
public int consecutiveNumbersSum(int N) {
int cnt = 0;
for (int i = 1; N > 0; N -= i, i++) {
cnt += (N % i == 0 ? 1 : 0);
}
return cnt;
}
复杂度分析
- 时间复杂度: ,
- 空间复杂度: ,
A_04 统计子串中的唯一字符
方法一:
复杂度分析
- 时间复杂度: ,
- 空间复杂度: ,