LeetCode:给定一个n个元素的数组,是否存在a,b,c三个元素,使用得a+b+c=0,找出所有符合这个条件的三元组

如题: 

 思路:

1. 先将数组排序

2.循环遍历数组元素,采用双指针法,如:当前元素下标为 i ,则低指针为  i+1, 高指针为 arr.length - 1 .

3. 如果三下标所对应元素的和 大于0,则 高指针减小一如果和小于0则低指针加一, 否则 则等于 0

4. 如果等于0,再判断有没有重复元素。

代码:

public class AddThreeToZero {

//=================================排序开始==========================

	public static void quickSort(int[] nums, int low, int high){  //快速排序
		int pivor = getPivor(low, high,nums);
		if(low < high){
			quickSort(nums, low, pivor - 1);
			quickSort(nums, pivor + 1, high);
		}
	}
	public static int getPivor(int low, int high, int[] arr){
		int pivorKey = arr[low];
		while(low < high){
			while(low < high && arr[high] >= pivorKey)
				high --;
			swap(low, high, arr);
			
			while(low < high && arr[low] <= pivorKey)
				low ++;
			swap(low, high, arr);
			
		}
		return low;
	}
	public static void swap(int i, int j, int[] arr){
		int temp = arr[i];
		arr[i] = arr[j];
		arr[j] = temp;
	}
//==================================排序结束===============================


	public static List<List<Integer>> threeSum(int[] nums) throws Exception {
		 HashMap<Integer, Integer> map = new HashMap<>();
		 quickSort(nums, 0, nums.length-1);
		 System.out.println("after sort:    " + Arrays.toString(nums));
		 List<List<Integer>> res = new ArrayList<List<Integer>>();
		 if(nums[0] > 0 || nums.length < 3)
			 throw new Exception("noooooo");
		 for(int i = 0; i < nums.length; i ++){
			 int left = i + 1, right = nums.length - 1;
			 while(left < right){
				 if(nums[i] + nums[left] + nums[right] > 0){
					 right --;
				 }else if(nums[i] + nums[left] + nums[right] < 0){
					 left ++;
				 }else{
					 System.out.println("left=====> " + left + ",   right=====> " + right);
					 List<Integer> list = new ArrayList<Integer>();
					 list.add(nums[i]);
					 list.add(nums[left]);
					 list.add(nums[right]);
					 if(res.contains(list)){
						  //already exists, do nothing
					 }else{
						 res.add(list);
					 }
					break;
				 }
				 
			 }
		 }
		return res;
	    }
	 public static void main(String[] args) throws Exception {
		int[] arr = {-1, 0, 1, 2, -1, -4};
		System.out.println(threeSum(arr).toString());
	}
	 
}

运行结果:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值