LeetCode - 1. Two Sum #Java

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.
Example:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
**UPDATE (2016/2/13):
**The return format had been changed to zero-based indices. Please read the above updated description carefully.

Solutions

渣渣表示只会用for循环,就不贴出O(n^2)的弱逼算法了。
去讨论区学习了下,大大们都用的HashMap,我去,HashMap这么高端的东西我长这么大一次都没用过啊!看看了思路,我觉得我是不是要转职了,没法混啊!

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        int[] result = null;
        
        for (int i = 0; i < nums.length; i++) {
            if (!map.containsKey(nums[i])) {
                map.put(target - nums[i], i);
            } else {
                int index = map.get(nums[i]);
                result = new int[]{index, i};
                break;
            }
        }
        
        return result;
    }
}

TO DO

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

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,355评论 0 33
  • 注:之前在其他平台的文章与记录慢慢也都放这边吧,权当资料迁移与备份。如下: LeetCode,最近才知道有这么好的...
    way菜畦阅读 8,977评论 5 7
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,493评论 0 23
  • 同班三年 跟你玩在一起也是因为一次的撕名牌 还记得那时候我跑太累回家时候没力气走你就帮我了拎书包感觉气氛还有些尴尬...
    ameii阅读 1,666评论 0 0
  • 葳蕤叶黄兮观九州苍莽, 楼兰大漠月未央。 时光荏苒兮非二九儿郎, 丝绸古道任翱翔。 黄沙漫漫兮怕戈壁且长, 夜半鬼...
    山野狂客阅读 2,790评论 0 1

友情链接更多精彩内容