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/

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容