双指针-two pointer
2021/12/26 6:07:12
本文主要是介绍双指针-two pointer,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
18. 4Sum
MediumGiven an array nums
of n
integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]]
such that:
0 <= a, b, c, d < n
a
,b
,c
, andd
are distinct.nums[a] + nums[b] + nums[c] + nums[d] == target
You may return the answer in any order.
Example 1:
Input: nums = [1,0,-1,0,-2,2], target = 0 Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
Example 2:
Input: nums = [2,2,2,2,2], target = 8 Output: [[2,2,2,2]]
Constraints:
1 <= nums.length <= 200
-109 <= nums[i] <= 109
-109 <= target <= 109
class Solution { public List<List<Integer>> fourSum(int[] nums, int target) { Arrays.sort(nums); List<List<Integer>> list = new ArrayList(); for(int a=0;a<nums.length-3;a++){ if(a>0 && nums[a]==nums[a-1]) continue; for(int b=a+1;b<nums.length-2;b++){ if(b>a+1 && nums[b]==nums[b-1]) continue; int temp = target-nums[a]-nums[b]; int left = b+1; int right = nums.length-1; while(left<right){ if(nums[left]+nums[right]==temp){ list.add(Arrays.asList(nums[a],nums[b],nums[left],nums[right])); left++;right--; while(left<right && nums[left]==nums[left-1]) left++; while(left<right && nums[right]==nums[right+1]) right--; } else if(nums[left]+nums[right]<temp){ left++; while(left<right && nums[left]==nums[left-1]) left++; } else{ right--; while(left<right && nums[right]==nums[right+1]) right--; } } } } return list; } }
这篇关于双指针-two pointer的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-12-24怎么修改Kafka的JVM参数?-icode9专业技术文章分享
- 2024-12-23线下车企门店如何实现线上线下融合?
- 2024-12-23鸿蒙Next ArkTS编程规范总结
- 2024-12-23物流团队冬至高效运转,哪款办公软件可助力风险评估?
- 2024-12-23优化库存,提升效率:医药企业如何借助看板软件实现仓库智能化
- 2024-12-23项目管理零负担!轻量化看板工具如何助力团队协作
- 2024-12-23电商活动复盘,为何是团队成长的核心环节?
- 2024-12-23鸿蒙Next ArkTS高性能编程实战
- 2024-12-23数据驱动:电商复盘从基础到进阶!
- 2024-12-23从数据到客户:跨境电商如何通过销售跟踪工具提升营销精准度?