• LeetCode & Q1-Two Sum-Easy


    Array Hash Table

    Question
    Given an array of integers, return indices of the two numbers such that they add up to a specific target.
    You may assume that each input would have exactly one solution, and you may not use the same element twice.
    Example:

    Given nums = [2, 7, 11, 15], target = 9,
    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].
    

    我的解答如下:

    public class Solution {
        public int[] twoSum(int[] nums, int target) {
            int[] temp = new int[2];
            for (int i = 0; i < nums.length - 1; i++) {
                for (int j = i + 1; j < nums.length; j++) {
                    if (nums[i] + nums[j] == target) {
                        temp[0] = i;
                        temp[1] = j;
                    }
                }
            }
            return temp;
        }
    }
    

    时间复杂度:$O(n^{2})$
    空间复杂度:$O(1)$

    最优解:

    public int[] twoSum(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++) {
            int complement = target - nums[i];
            if (map.containsKey(complement) && map.get(complement) != i) {
                return new int[] { i, map.get(complement) };
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }
    

    时间复杂度为:$O(n)$

  • 相关阅读:
    检索COM类工厂中CLSID为{00024500-0000-0000-C000-000000000046}的组件时失败
    VSTO 开发中 应用ActionPane、CustomTaskPane
    Thread.Join()的详解
    HBase笔记
    Hive命令详解
    视频地址
    几种表
    如何将数据导入到hive中
    hdfs笔记
    分区表简介
  • 原文地址:https://www.cnblogs.com/duyue6002/p/6850645.html
Copyright © 2020-2023  润新知