diff --git a/notes/Leetcode 题解 - 双指针.md b/notes/Leetcode 题解 - 双指针.md index 1fea1b9c..2a96ab50 100644 --- a/notes/Leetcode 题解 - 双指针.md +++ b/notes/Leetcode 题解 - 双指针.md @@ -39,9 +39,9 @@ Output: index1=1, index2=2 这样移动不会错过答案:sum \< target 时,numbers[i] 与 i、j 之间任何元素的和都不超过 sum,i 不可能属于答案;sum \> target 时同理排除 j。 -数组中的元素最多遍历一次,时间复杂度为 O(N)。只使用了两个额外变量,空间复杂度为 O(1)。 +数组中的元素最多遍历一次,时间复杂度为 O(N)。只使用了两个额外变量,空间复杂度为 O(1)。 -

+

```java public int[] twoSum(int[] numbers, int target) { @@ -82,21 +82,21 @@ Explanation: 1 * 1 + 2 * 2 = 5 因为最多只需要遍历一次 0\~sqrt(target),所以时间复杂度为 O(sqrt(target))。又因为只使用了两个额外的变量,因此空间复杂度为 O(1)。 ```java - public boolean judgeSquareSum(int target) { - if (target < 0) return false; - int i = 0, j = (int) Math.sqrt(target); - while (i <= j) { - long powSum = (long) i * i + (long) j * j; - if (powSum == target) { - return true; - } else if (powSum > target) { - j--; - } else { - i++; - } - } - return false; - } +public boolean judgeSquareSum(int target) { + if (target < 0) return false; + int i = 0, j = (int) Math.sqrt(target); + while (i <= j) { + long powSum = (long) i * i + (long) j * j; + if (powSum == target) { + return true; + } else if (powSum > target) { + j--; + } else { + i++; + } + } + return false; +} ``` ## 3. 反转字符串中的元音字符 @@ -118,7 +118,7 @@ Given s = "leetcode", return "leotcede". - 时间复杂度为 O(N):只需要遍历所有元素一次; - 空间复杂度为 O(N):Java 的字符串不可修改,需要一个与 s 等长的字符数组保存结果。 -

+

```java private final static HashSet vowels = new HashSet<>( @@ -156,13 +156,13 @@ Output: True Explanation: You could delete the character 'c'. ``` -题目描述:可以删除一个字符,判断是否能构成回文字符串。 +题目描述:最多删除一个字符,判断能否构成回文字符串。 所谓的回文字符串,是指具有左右对称特点的字符串,例如 "abcba" 就是一个回文字符串。 使用双指针可以很容易判断一个字符串是否是回文字符串:令一个指针从左到右遍历,一个指针从右到左遍历,这两个指针同时移动一个位置,每次都判断两个指针指向的字符是否相同,如果都相同,字符串才是具有左右对称性质的回文字符串。 -

+

本题的关键是处理删除一个字符。在使用双指针遍历字符串时,如果出现两个指针指向的字符不相等的情况,就试着删除一个字符,再判断删除完之后的字符串是否是回文字符串。 @@ -170,7 +170,7 @@ Explanation: You could delete the character 'c'. 在试着删除字符时,既可以删除左指针指向的字符,也可以删除右指针指向的字符。 -

+

```java public boolean validPalindrome(String s) {