zoukankan      html  css  js  c++  java
  • 1. Two Sum

    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.

    Example:
    Given nums = [2, 7, 11, 15], target = 9,

    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].

    Solution: 暴力遍历 时间复杂度是O(n2); 使用Hashmap, 时间复杂度O(n)

    public class Solution {
        public int[] twoSum(int[] nums, int target) {
            int[] result = new int[2];
            int key;
            HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>(); //constructor of hashmap
            for(int i = 0; i < nums.length; i++){ //traverse array
                hashMap.put(nums[i], i); //insert hashmap
            }
            
            for(int i = 0; i < nums.length; i++){
                key = target-nums[i];
                if(hashMap.containsKey(key)
                  && hashMap.get(key)!=i){//cannot be itself
                    result[0] = i;
                    result[1] = hashMap.get(key); //hashmap get value
                    break;
                }
            }
            return result;
        }
    }
  • 相关阅读:
    datagrid
    IntelliJ IDEA for mac 引入js注意事项
    centos7安装并配置svn
    yum使用总结
    安装php
    类视图
    django里面添加静态变量
    Ubuntu16.04安装&创建虚拟环境
    制作dockerfile, 天眼查的镜像、并运行
    dockerfile
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/5448060.html
Copyright © 2011-2022 走看看