class Solution {
public int[] twoSum(int[] numbers, int target) {
int left=0, right=numbers.length-1;
while(left < right){
if(numbers[left]+numbers[right]== target){
return new int[]{left+1, right+1};
}
if(numbers[left]+numbers[right] > target){
right--;
}
if(numbers[left]+numbers[right] < target){
left++;
}
}
return new int[]{-1, -1};
}
}
给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。
找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
返回容器可以储存的最大水量。
**说明:**你不能倾斜容器。
解:考虑移位的条件
class Solution {
public int maxArea(int[] height) {
int left=0, right=height.length-1;
int max=Integer.MIN_VALUE;
while(left < right ){
max =Math.max(max,(right -left) * Math.min(height[left], height[right]));
if(height[left]>=height[right]){
right--;
}else{
left++;
}
}
return max;
}
}
给你一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != j、i != k 且 j != k ,同时还满足 nums[i] + nums[j] + nums[k] == 0 。请
你返回所有和为 0 且不重复的三元组。
**注意:**答案中不可以包含重复的三元组。
解: 先排序,然后后面的两元组分别左右遍历。
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
int n = nums.length;
Arrays.sort(nums);
List<List<Integer>> ans = new ArrayList<List<Integer>>();
for(int first=0; first< n; first++){
//剔除重复的元素
if(first> 0 && nums[first] == nums[first-1]){
continue;
}
int third = n-1;
int target = -nums[first];
for(int second =first +1; second< n ; second++){
//剔除重复的元素
if(second > first+1 && nums[second] == nums[second-1]){
continue;
}
//移动最后的指针,找到最后一个 nums[second]+ nums[third] <=target的位置
while(second< third && nums[second]+ nums[third] > target){
--third;
}
//循环结束
if(second==third){
break;
}
//添加到列表中
if (nums[second] + nums[third] == target) {
List<Integer> list = new ArrayList<Integer>();
list.add(nums[first]);
list.add(nums[second]);
list.add(nums[third]);
ans.add(list);
}
}
}
return ans;
}
}