N数之和

95 篇文章 0 订阅

 两数之和

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        Map<Integer, Integer> map = new HashMap();
        for(int i=0;i<nums.length;++i){
            if(map.containsKey(target - nums[i])){
                result[0] = map.get(target-nums[i]);
                result[1] = i;
                return result;
            }
            map.put(nums[i], i);
        }
        return result;
    }
}

 

## 三数之和

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        Map<Integer, Integer> map = new HashMap();
        for(int i=0;i<nums.length;++i){
            map.put(-1*nums[i], i);
        }
        List<List<Integer>> result = new ArrayList();
        for(int i=0;i<nums.length;++i){
            for(int j=i+1;j<nums.length;++j){
                if(map.containsKey(nums[j]+nums[i]) && map.get(nums[j]+nums[i])>j){
                    List<Integer> temp = new ArrayList();
                    temp.add(nums[i]);
                    temp.add(nums[j]);
                    temp.add(-1*(nums[j]+nums[i]));
                    if(result.contains(temp)){
                        continue;
                    }
                    result.add(temp);
                }
            }
        }
        return result;
    }
}

 

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList();
        if(nums == null || nums.length < 3){
            return result;
        }
        Arrays.sort(nums);
        for(int i=1;i<nums.length-1;++i){
            int l = 0, r = nums.length-1;
            while(l < i && r > i){
                if(nums[l]>0 || nums[l] + nums[i] > 0)break;
                int sum = nums[l]+nums[i]+nums[r];
                if(sum == 0){
                    List<Integer> temp = Arrays.asList(nums[l], nums[i], nums[r]);
                    if(!result.contains(temp)){
                        result.add(temp);
                    }
                    while(nums[l] == nums[l+1] && l+1 < i)++l;
                    while(nums[r] == nums[r-1] && r-1 > i)--r;
                    ++l;
                    --r;
                }else if(sum>0){
                    --r;
                } else{
                    ++l;
                }
            }
        }
        return result;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值