A-两数之和

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

方法一:遍历每个元素x,查找是否存在一个值与 target -x 相等。
    public int[] twoSum(int[] nums, int target) {
        if (nums.length <2 || target < 0) throw new IllegalArgumentException("参数不合法!");
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[j] == target - nums[i]){
                    return new int[]{i,j};
                }
            }
        }
        throw new IllegalArgumentException("未找到匹配的参数!");
    }

时间复杂度:O(n^2),空间复杂度:O(1)

方法二:空间换时间。第一次遍历数组将数组的元素和下标放至HashMap中,第二次遍历数组判断HashMap中是否存在target-num[i]的key,且不能为同一元素。

注:此方法不允许数组中存在重复元素。

    public int[] twoSum(int[] nums, int target) {
        if (nums.length < 2 || target < 0) throw new IllegalArgumentException("参数不合法!");
        Integer size = new Double(nums.length / 0.75 + 1).intValue();
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(size);
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], i);
        }

        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i]) && map.get(target - nums[i]) != i) {
                return new int[]{i, map.get(target - nums[i])};
            }
        }
        throw new IllegalArgumentException("未找到匹配的参数!");
    }

时间复杂度:O(n),空间复杂度:O(n)

方法三:同方法二,但只进行一次遍历
    public int[] twoSum(int[] nums, int target) {
        if (nums.length < 2 || target < 0) throw new IllegalArgumentException("参数不合法!");
        Integer size = new Double(nums.length / 0.75 + 1).intValue();
        HashMap<Integer, Integer> map = new HashMap<>(size);
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (map.containsKey(complement)) {
                return new int[]{map.get(complement), i};
            }
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("未找到匹配的参数!");
    }

时间复杂度:O(n),空间复杂度:O(n)

测试用例:

    public static void main(String[] args) {
        Solution s = new Solution();
        int[] result = s.twoSum(new int[]{1,3,6,8,4},5);
//        int[] result = s.twoSum(new int[0],3);
//        int[] result = s.twoSum(new int[]{1,3,6,8,4},-1);
//        int[] result = s.twoSum(new int[]{1,3,6,8,4},100);

        for (int i:result) System.out.print(i + " ");
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值