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;
        }
    }
  • 相关阅读:
    yii主题
    aptana studio 使用技巧整理
    big database url
    yii表单输入元素
    下载,和scp上传问题
    对缓存的思考——提高命中率
    php用户名密码
    openx -书表添加字段
    搜索
    python——常用模块2
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/5448060.html
Copyright © 2011-2022 走看看