Java算法之TwoSum

给定一个int数组,其中两个数相加等于一个特定值,返回这两个数的索引

示例

int数组: [2, 7, 11, 15], 特定值 : 9,
因为: nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

解决方案

package com.zss;

import java.util.HashMap;
import java.util.Map;

public class Solution {
    public static void main(String[] args) {
        int[] location = twosum2(new int[]{2, 8, 11, 7, 15}, 9);
        for (int i = 0; i < location.length; i++) {
            System.out.print(location[i]);
        }

    }

    /**
     * 空间复杂度O(1)
     * 时间复杂度O(n*n)
     *
     * @param nums
     * @param target
     * @return
     */
    public static int[] twosum(int[] nums, int target) {
        int[] location = new int[]{0, 1};
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    location[0] = i;
                    location[1] = j;
                }
            }
        }
        return location;
    }

    /**
     * 空间复杂度O(n)
     * 时间复杂度O(n)
     *
     * @param nums
     * @param target
     * @return
     */
    public static int[] twosum2(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        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("no solution");
    }

    /**
     * 时间复杂度O(n)
     * 空间复杂度O(n)
     *
     * @param nums
     * @param target
     * @return
     */
    public static int[] twosum3(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (map.containsKey(complement)) {
                return new int[]{i, map.get(complement)};
            }
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("No solution");
    }
}

参考

https://leetcode.com/problems/two-sum/description/

    原文作者:小菜鸟程序媛
    原文地址: https://www.jianshu.com/p/e4a0c82cb143
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞