Two Sum

一直听说LeetCode,今天第一次刷题,之前没有接触过算法,记录自己的刷题。
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]
思路:两个数整数相加等于targe,且数组中都为大于零,故需要查找targe-x的位置
解法:
public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; i++) {
            int temp = nums[i];
            if (map.containsKey(temp)) {
                result[0] = map.get(temp);
                result[1] = i;
                return result;
            }
            //如果没有,就put到map里面
            else {
                map.put(target - nums[i], i);
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }

这道题作为第一题还是很简单的,开始想把数组通过asList转为List,通过indexof去查找targe-x的位置。 后来突然想到8 个基本类型是无法作为 asList 的参数的。 所以换成map
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 虽然目前工作上不需要自己写算法,但还是想写点记录下什么。这里推荐个刷题网站LeetCode,如果你是个大学未毕业的...
    JimWithJiang阅读 189评论 0 0
  • Given an array of integers, return indices of the two num...
    stevewang阅读 304评论 0 1
  • 一、前言 LeetCode也支持Swift了,离职在家,闲来无事,便想着刷几道玩玩,既可以学习一下算法,又可以保持...
    BreadAwesome阅读 269评论 0 1
  • 果然是好久没有刷oj了感觉脑子都不转了 希望在这段时间乃至以后每天都能刷一刷 你看到的别人的辉煌都是付出了一定努力...
    ninee阅读 159评论 0 0
  • 他睁开眼。 窗帘缝中透出的阳光铺在手上,他感受着手下传来的温暖,看到握着的另一只手。 他看向左侧,身边的女孩安睡着...
    呼吸不说谎阅读 210评论 0 0