LeetCode 1. Two Sum 两数之和 Java实现

最近准备面试题目,开个新坑慢慢填... ==

题目:

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

示例:

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

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

这道题最简单的做法就是针对nums里面的每一个元素,与target求差,然后在nums里面找有没有等于这个差值的元素。

import java.util.*;
public class TwoSum {
    public int[] twoSumBrute(int[] nums, int target) {
        int[] result = new int[2];
        if (nums == null || nums.length < 2) return null;
        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] == target - nums[j]) {
                    result[0] = i;
                    result[1] = j;
                }
            }
        }
        return result;
    }
}

求解的时间复杂度是O(N^2),效果并不是很好。可以使用哈希表优化,让寻找差值是否在nums中这个操作的时间复杂度从O(N)下降到O(1),整体时间复杂度变为O(N),性能得到极大提升。

import java.util.*;
public class NumAdd1 {
    public int[] twoSumHash(int[] nums, int target) {
        int [] result = new int[2];
        if (nums == null || nums.length < 2) return null;
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                result[1] = i;
                result[0] = map.get(target - nums[i]);
                break;
            }
            map.put(nums[i], i);
        }
        return result;
    }
}

猜你喜欢

转载自blog.csdn.net/zhangzhetaojj/article/details/80018684