LeetCode1两数之和、15三数之和

1. 两数之和

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

15.三数之和

给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。

注意:答案中不可以包含重复的三元组。

示例:

给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]

solution1 暴力破解

//两次循环解两数之和
class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] re = new int[2];
        for (int i = 0; i < nums.length - 1; i ++) {
            for (int j = i + 1; j < nums.length; j ++){
                if (nums[i] + nums[j] == target) {
                    re[0] = i;
                    re[1] = j;
                    break;
                }
            }
        }
        return re;
    }
}
//三次循环解三数之和,超出时间限制
class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        if (nums == null || nums.length <= 2) {
            return Collections.emptyList();
        }
        // Set集合,去除重复的数组
        Set<List<Integer>> re = new LinkedHashSet<>();
        for (int t = 0; t < nums.length - 2; t ++) {
            for (int i = t + 1; i < nums.length - 1; i ++){
                for (int j = i + 1; j < nums.length; j ++) {
                    if (nums[t] + nums[i] + nums[j] == 0) {
                        List<Integer> value = Arrays.asList(nums[t],nums[i],nums[j]);
                        Collections.sort(value);
                        re.add(value);
                    }
                }
            }
        }
        return new ArrayList<>(re);
    }
}

solution2 两指针

//时间复杂度n^2 
//先排序然后遍历数组,整两指针向中夹逼
class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        if (nums == null || nums.length <= 2) {
            return Collections.emptyList();
        }
       Arrays.sort(nums);
       List<List<Integer>> res = new LinkedList<>();
       for (int k = 0; k < nums.length - 2; k ++) {
           if (nums[k] > 0) return res;
           if (k > 0 && nums[k] == nums[k-1]) continue;
           if(k == 0 || k >= 0 && nums[k] != nums[k - 1]) {
               for (int i = k + 1,j = nums.length - 1; i < j;){
                    int sum = nums[i] + nums[j];
                    int min = 0 - nums[k];
                    if (sum == min) {
                        res.add(Arrays.asList(nums[i],nums[j],nums[k]));
                        while(i < j && nums[i] == nums[i+1]) i ++;
                        while(i < j && nums[j] == nums[j-1]) j --;
                        i ++;
                        j --;
                    }
                    else if (sum < min) {
                        i ++;
                    }else j --;
                }
           }
       }
       return res;
    }
}

哈希表法

猜你喜欢

转载自www.cnblogs.com/gg12138/p/12902488.html