LeetCode热题100道-Day03
- 使用双指针解题,这道题求盛水最多就是求两数乘积最大。求面积最大,左指针在头,右指针在尾,对数组遍历,求对面积记录,通过函数取它们的最大值。同时在遍历时,面积宽度在缩小,移动的是两端高度较低的一侧,最后返回最大面积max。
class Solution {
public int maxArea(int[] height) {
int left = 0, right = height.length - 1;
int max = 0;
while (left < right) {
int ans = (right - left) * Math.min(height[left], height[right]);
max = Math.max(ans, max);
if (height[left] < height[right]) ++left;
else --right;
}
return max;
}
}
- 使用双指针解题,首先对数组进行排序,对特例进行排除,对第一个数进行去重,i从下标0的地方开始,同时定一个下标 left 定义在i+1的位置上,定义下标 right 在数组结尾的位置上,sum = nums[i] + nums[left] + nums[right] ,再对第二个数num[left]和第三个数nums[right]去重,找到结果后,left和right收缩。
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
int len = nums.length;
if (nums[0] > 0 || nums[len - 1] < 0) return result;
for (int i = 0; i < len; i++) {
if (nums[i] > 0) {
return result;
}
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int left = i + 1;
int right = len - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum < 0) {
++left;
} else if (sum > 0) {
--right;
} else {
result.add(Arrays.asList(nums[i], nums[left], nums[right]));
while (left < right && nums[left] == nums[left + 1]) left++;
while (left < right && nums[right] == nums[right - 1]) right--;
left++;
right--;
}
}
}
return result;
}
}
class Solution {
List<String> result = new ArrayList<>();
StringBuilder temp = new StringBuilder();
public List<String> letterCombinations(String digits) {
if (digits.length() == 0) {
return result;
}
String[] letterMap = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
backTracking(digits, letterMap, 0);
return result;
}
public void backTracking(String digits, String[] letterMap, int index) {
if (index == digits.length()) {
result.add(temp.toString());
return;
}
String str = letterMap[digits.charAt(index) - '0'];
for (int i = 0; i < str.length(); i++) {
temp.append(str.charAt(i));
backTracking(digits, letterMap, index + 1);
temp.deleteCharAt(temp.length() - 1);
}
}
}