`
notlcry
  • 浏览: 1942 次
  • 性别: Icon_minigender_1
  • 来自: 上海
最近访客 更多访客>>
社区版块
存档分类
最新评论

LeetCode-(1) Two Sum

阅读更多

 问题地址:https://oj.leetcode.com/problems/two-sum/

问题描述:
Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
思路:
1.因为只有唯一解,所以任意两个元素和为唯一元素。最先想到的是,穷举法,把所有2个元素相加,则得到一个值,如果是Target,则得到解。该方法可行。
判断该方法的复杂度:1+2+3+4+5+...+n= ,即 
考虑有没有更快的方法:
2.通过Target减去数组元素,然后得到被减数,在数组中查找。通过Target减去一个元素,然后在剩余元素中取查找被减数。这样好像更方便,但是其实和上面方法1的复杂度是一样的,即 。
3.空间换时间,在方法2的基础上,如果能把在剩余元素中查找的复杂度从O(n)变为O(1),整体复杂度就会从变到O(n)。如果把查找变为O(1)呢,当然是Hash表了。因为要返回元素的小标,所以,这里用了hashMap,如果不需要下标,只需要2个元素的值,则可以用HashSet。OK,方法正确。开始实现。
几点注意事项:
1)因为需要小标,所有Map的key是元素的值,Value应该是小标,所以Map应该是 Map<int,int>。但是存在这样的问题,可能存在值相同的元素,这样的话Key相同,之前的下标会被覆盖掉。所以Value应该是一个链表或者数组,下面的code中用了Arraylist。
2)注意小标是从1开始的。
3)要求index1 must be less than index2,所以遍历的时候从0~n遍历。
4)如果是T=X+X这样情况,要避免找到相同的第一个小标,所有要跳过自己。
 Code:
public int[] twoSumNotSame(int[] numbers, int target) {
		int[] a = new int[2];
		HashMap<Integer, ArrayList<Integer>> map = 
new HashMap<Integer, ArrayList<Integer>>(numbers.length);
		for (int i = 0; i < numbers.length; i++) {
			if (map.get(numbers[i]) == null) {
				ArrayList<Integer> list = new ArrayList<Integer>();
				list.add(i);
				map.put(numbers[i], list);
			} else {
				map.get(numbers[i]).add(i);
			}
		}

		ArrayList<Integer> rsList = null;
		int firstIndex = 0;
		for (int i = 0; i < numbers.length; i++) {
			if (map.get(target - numbers[i]) != null) {
				rsList = map.get(target - numbers[i]);
				if (rsList.size() == 1 && rsList.get(0) == i) {
					continue;
				}
				firstIndex = i;
				break;
			}
		}
		int secondIndex = 0;
		for (Integer e : rsList) {
			if (e != firstIndex) {
				secondIndex = e;
				break;
			}
		}
		a[0] = firstIndex + 1;
		a[1] = secondIndex + 1;
		return a;
	}
 UT:
@Test
	public void t1NotEquals() {
		int[] numbers = { 2, 7, 11, 15 };
		int target = 9;
		int[] a = solution.twoSumWithSame(numbers, target);
		Assert.assertEquals(1, a[0]);
		Assert.assertEquals(2, a[1]);

	}

	@Test
	public void t2NotEquals2() {
		int[] numbers = { 20, 4, 11, 15, 3, 5, 9 };
		int target = 13;
		int[] a = solution.twoSumWithSame(numbers, target);
		Assert.assertEquals(2, a[0]);
		Assert.assertEquals(7, a[1]);

	}

	@Test
	public void t3Equals() {
		int[] numbers = { 2, 4, 6, 7 };
		int target = 8;
		int[] a = solution.twoSumWithSame(numbers, target);
		Assert.assertEquals(1, a[0]);
		Assert.assertEquals(3, a[1]);

	}

	@Test
	public void t4Equals2() {
		int[] numbers = { 2, 4, 6 };
		int target = 12;
		int[] a = solution.twoSumWithSame(numbers, target);
		Assert.assertEquals(3, a[0]);
		Assert.assertEquals(3, a[1]);

	}
 思考:
     空间换时间是一种常用的方法,可以通过缓存数据,或者做映射,来降低时间复杂度。
  • 大小: 531 Bytes
  • 大小: 414 Bytes
分享到:
评论

相关推荐

    leetcode和oj-leetcode-1-Two-Sum:解决方案

    leetcode-1-Two-Sum 这是我在 Github 的第一天。 我只是 AC leetcode 中的第一个问题。 从现在开始,我将使用Github在leetcode中记录我的生活。 我擅长 C++,但对 java 和 Python 不是很专业,我将使用最流行的 3 种...

    leetcodepython001-leetcode-problems-crawler:leetcode-问题-爬虫

    001.two-sum │  ├── information.json │  ├── README.md ├── 002.add-two-numbers │  ├── information.json │  ├── README.md ... 有一些有用的选项: Options: -r, --rule crawling rule, ...

    vscode安装leetcode-leetcode-js-tdd:LeetCode勇士的简单样板

    twoSum , cases : [ { in : [ [ 2 , 7 , 11 , 15 ] , 9 ] , out : [ 0 , 1 ] } , { in : [ [ 11 , 2 , 15 , 7 ] , 9 ] , out : [ 1 , 3 ] } , ] , } npm start 特征 忽视问题 如果导出ignore: true则可以忽略问题 ...

    Algorithm-LeetCode-Solution-From-GuaZiDou.zip

    例如,"Two Sum"问题要求在给定整数数组和一个目标值,找出数组中和为目标值的那两个整数。这个问题可以使用哈希表来解决,通过一次遍历,将元素及其索引存入哈希表,然后再次遍历,检查目标值减去当前元素是否存在...

    离线和leetcode-leetcode-cli-2.6.1:leetcode-cli-2.6.1

    离线和leetcode leetcode-cli 一个享受 leetcode 的高效 cli 工具! 非常感谢 leetcode.com,一个非常棒的网站!...⦙⦙⦙⦙⦙⦙⦙⦙ ...leetcode.com。...leetcode ...leetcode ...leetcode ...leetcode ..../two-sum.cpp

    离线和leetcode-leetcode-cn-cli:为leetcode-cn.com工作

    离线和leetcode leetcode-cli 一个享受 leetcode 的高效 cli 工具! 非常感谢 leetcode.com,一个非常棒的网站!...⦙⦙⦙⦙⦙⦙⦙⦙ ...leetcode.com。...leetcode ...leetcode ...leetcode ...leetcode ..../two-sum.cpp

    leetcode答案-leetcode-machine-swift:Xcode中的leetcode解决方案验证

    leetcode 答案 leetcode-machine-swift :SOS_button: 请帮助在Sources/leetcode-machine-swift/leetcode.swift设置所有 leetcode 问题。...1 : Question ( name : " Two Sum " , inputs : [([ 2 , 7

    leetcode答案-leetcode:leetcode-问题

    https://leetcode-cn.com/problems/two-sum/ 难度 : 简单 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。...

    leetcode2-leetcode-training:算法训练

    leetcode 2 leetcode-训练 算法训练。 java $: javac hello.java java ...leetcode ...leetcode ...leetcode ...leetcode ...1.two-sum.cpp leetcode test 1.two-sum.cpp leetcode test 1.two-sum.cpp -t '[1,2,3]\n3'

    leetcode-master.zip

    1. "001_two_sum":这是LeetCode的第一道题目,名为“两数之和”。该问题要求在给定整数数组中找到两个元素,使得它们的和等于一个特定的目标值。你需要返回这两个元素的索引。这是一个基础的哈希表应用,通过遍历...

    leetcode不会-1TwoSum:leetcode-1二和

    leetcode 不会1. 二和 资源: 优化搜索无序列表 你不能。 您能做的最好的事情是分解搜索任务并使用并发或并行来加速搜索任务。 从最后一个索引遍历数组 范围运算符只能以增量方式工作。 // In Kotlin/Swift // this ...

    leetcode-leetcode-helper:节省您为每个leetcode问题构建脚手架的时间

    leetcode 只专注于解决方案! leetcode-helper是一个单 jar 库,它使您无需为每个问题设置解决方案测试脚手架。 生成解决方案/测试框架,编译,通过一行命令进行测试。 集成了Junit ...two_sum/ │  └──

    js代码-1. 两数之和 [简单] https://leetcode-cn.com/problems/two-sum

    function twoSum(nums, target) { const map = new Map(); for (let i = 0; i ; i++) { const complement = target - nums[i]; if (map.has(complement)) { return [map.get(complement), i]; } map.set(nums...

    leetcode编辑器-leetcode-question:leetcode-问题

    leetcode编辑器leetcode-问题 自定义代码演示 leetcode 编辑器配置 代码文件名: $ ! velocityTool . camelCaseName(${question ...com.shuzijun.leetcode.editor.en...title ex:Two Sum ${question.titleSlug} question t

    leetcode答案-Two-Sum:leetcode两数之和代码

    Two-Sum leetcode两数之和代码 题目描述:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,数组...

    leetcode和oj-LeetCode-1:算法实践项目

    _001_TwoSum | | | | |-- twoSum.java | | | | |-- twoSum.kt | | | | |-- twoSum.md | |-- ...... 非常欢迎讨论和代码审查。 TwoSum.java在 Java 中提供了 OJ 接受的解决方案。 TwoSum.kt在 Kotlin 中提供 OJ 接受...

    leetcode答案-leetcode-solution:leetcode-解决方案

    twoSum = function(nums, target) { const { length } = nums for(let i = 0; i &lt; length - 1; i++) { for(let j = i + 1; j &lt; length; j++) { if(nums[i] + nums[j] === target) { return [i, j] } } } } // ...

    LeetCode-Hot-100

    例如,"Two Sum"问题要求你在数组中找到两个数,使得它们的和等于一个特定的目标值,这涉及到哈希表的使用来实现快速查找。"Merge Intervals"则要求合并重叠的区间,考察了排序和区间操作技巧。 2. **算法**:题目...

    leetcode接口-leetcodeHelper:leetcodeHelper

    leetcode 接口 该项目可帮助您使用首选的 IDE 或带有命令行界面 (CLI) 的编辑器来执行 ...two-sum leetcode --name add-two-numbers leetcode --name median-of-two-sorted-arrays 然后问题描述和启动代码将自动

    leetcode答案-leetcode-php:leetcode-php

    例如,如果有一个文件名为`1_two_sum.php`,那么它可能对应的是LeetCode的第一题——两数之和。在这些文件中,你可以找到完整的PHP代码,用于解决特定的算法问题。 在学习这个项目的过程中,你可以关注以下几个方面...

Global site tag (gtag.js) - Google Analytics