博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Two Sum
阅读量:6572 次
发布时间:2019-06-24

本文共 1945 字,大约阅读时间需要 6 分钟。

public class Solution {    public int[] twoSum(int[] nums, int target) {         /* Basic idea: Load the array into a hashMap with the value of each array element as key and index of the array as value           Interate through the key, and check whether "target - value" is in the map.            Save the array index and sort it                      Special case: The array contains duplicate elements.             1) The target value is not or only related to the one of the duplicate value => store the first one.           2) The target value is twice of the duplicate value => directly store the two indexes and return output.        */                int[] results = new int[2];        Map
numsMap = new HashMap
(); for (int i = 0; i < nums.length; i++){ if (numsMap.containsKey(nums[i])){ /*It has duplicated number if 1) duplication is the results, return 2) drop the second, if it is put back to the map, value(index) got overide */ if (2 * nums[i] == target){ results[0] = numsMap.get(nums[i]); // it stores as index when the Hash is created results[1] = i + 1; // i start at 0, so need to +1 as index return results; } } else { numsMap.put(nums[i], i+1); //the array index start at 0; } } for(Integer key : numsMap.keySet()){ if (numsMap.containsKey(target - key)){ int a = numsMap.get(key); int b = numsMap.get(target-key); if (a < b){ results[0] = a; results[1] = b; } else { results[0] = b; results[1] = a; } } } return results; }}

 

转载于:https://www.cnblogs.com/codingEskimo/p/5032291.html

你可能感兴趣的文章
Android 开发之 bindService() 通信
查看>>
PC-如何禁用 Cookie
查看>>
poj 1094
查看>>
如何做一份能忽悠投资人的PPT
查看>>
Java 基础【13】 I/O流概念分析整理
查看>>
数据结构 单一列表
查看>>
Spark入门实战系列--3.Spark编程模型(上)--编程模型及SparkShell实战
查看>>
和“黑凤梨”一样搞笑的谐音词
查看>>
EM算法(Expectation Maximization Algorithm)
查看>>
C# 操作iis6、iis7 301
查看>>
从零开始学 iOS 开发的15条建议
查看>>
SQL Server 合并复制遇到identity range check报错的解决
查看>>
深入理解C# 静态类与非静态类、静态成员的区别
查看>>
精灵菜单
查看>>
【Leetcode】Path Sum II
查看>>
设计模式 总揽 通过这篇随笔可以访问所需要了解的设计模式
查看>>
Photoshop和WPF双剑配合,打造炫酷个性的进度条控件
查看>>
2014最不受欢迎10编程语言种
查看>>
LVM逻辑卷管理@设备、格式、摩、引导自己主动安装一个完整的章节
查看>>
iOS 开发笔记-加载/初始化
查看>>