leetcode(Two Sum)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsx1612727380/article/details/84205753

Title:Two Sum     1

Difficulty:Easy

原题leetcode地址:https://leetcode.com/problems/two-sum/

下面主要是3种解法:

1. 暴力法,时间&空间复杂度如下:

时间复杂度:O(n^2),两层for循环,每一层for循环再没有找到对应的target时,都是要执行n次。

空间复杂度:O(1),申请了一维长度为2数组。

    /**
     * 暴力法
     * @param nums
     * @param target
     * @return
     */
    public static int[] twoSum(int[] nums, int target) {
        int index[] = new int[]{0, 1};

        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; i < nums.length; j++) {
                if (target == nums[i] + nums[j]) {
                    index[0] = i;
                    index[1] = j;
                }
            }
        }

        return index;
    }

2. 采用Set集合的唯一性,时间&空间复杂度如下:

时间复杂度:O(n),虽然代码中包含了两层for循环,但是不是在第一层时,第二层每次都需要执行一次for循环。

空间复杂度:O(n),申请了HashSet,最长为n。

    /**
     * 利用Set集合的唯一性
     * @param nums
     * @param target
     * @return
     */
    public static int[] twoSum2(int[] nums, int target) {
        int index[] = new int[]{0, 1};
        Set hset = new HashSet();

        for (int i = 0 ; i < nums.length; i++) {
            if (hset.add(target - nums[i])) {
                hset.remove(target - nums[i]);
                hset.add(nums[i]);
            } else {
                index[1] = i;
                for (int j = 0; j < i; j++) {
                    if (target == (nums[i] + nums[j])) {
                        index[0] = j;
                    }
                }
            }
        }

        return index;
    }

3. 采用Map的Key的唯一性,时间&空间复杂度如下:

时间复杂度:O(n),一层for循环,最长遍历时数据的长度。

空间复杂度:O(n),申请了HashMap,最长为n。

    /**
     * 利用Map的Key唯一性
     * @param nums
     * @param target
     * @return
     */
    public static int[] twoSum3(int[] nums, int target) {
        int index[] = new int[]{0, 1};
        Map<Integer, Integer> hmap = new HashMap<Integer, Integer>();

        for (int i = 0; i < nums.length; i++) {
            if (hmap.containsKey(target - nums[i])) {
                index[0] = hmap.get(target - nums[i]);
                index[1] = i;
            }
            hmap.put(nums[i], i);
        }

        return index;
    }

猜你喜欢

转载自blog.csdn.net/hsx1612727380/article/details/84205753