Two Sum和Three Sum

本文详细介绍了TwoSum和ThreeSum的经典算法实现。TwoSum问题要求从整数数组中找出两个数,使它们的和等于特定的目标值;ThreeSum问题则需找出三个数,使它们的和为零。文章提供了完整的Java代码示例,包括使用哈希表优化TwoSum的解决方案,以及采用双指针技巧解决ThreeSum的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Two Sum和Three Sum

1.Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
public int[] twoSum(int[] nums, int target) {
         HashMap< Integer, Integer> map=new HashMap<Integer,Integer>();
         int []res=new int[2];
         int n=nums.length;
         for(int i=0;i<n;i++){
             map.put(nums[i],i);
         }
         for(int i=0;i<n;i++){
             int t=target-nums[i];
             if(map.containsKey(t)&&map.get(t)!=i){
                 res[0]=i;
                 res[1]=map.get(t);
                 break;
             }
         }
         return res;
     }

2.Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note: The solution set must not contain duplicate triplets.

For example, given array S = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]
List<List<Integer>> res=new ArrayList<List<Integer>>();
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);   //排序的时间复杂度为O(n*lgn);
        int len=nums.length;
        for(int i=0;i<len-2;i++){
            if(i>0&&nums[i]==nums[i-1])
                continue;                   //跳过相同的结果
            int l=i+1;
            int r=len-1;
            int target=nums[i];
        while(l<r){
            if(nums[l]+nums[r]+target==0){
                res.add(Arrays.asList(nums[l],nums[r],target));
                while(l<r&&nums[l]==nums[l+1]) l++;     //跳过重复的结果
                while(l<r&&nums[r]==nums[r-1]) r--;   //跳过重复的结果
                l++;
                r--;
            }
            else if(nums[l]+nums[r]+target<0){
                l++;
            }
            else{
                r--;
            }
        }   //找到与num[i]相加等于0地两个数。
    }
        return res;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值