Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d524f8a

Browse files
committed
two sum
1 parent 0b2c305 commit d524f8a

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

‎Two Sum.java

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/*
2+
题目:
3+
链接:https://leetcode.com/problems/two-sum/description/
4+
5+
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
6+
7+
You may assume that each input would have exactly one solution, and you may not use the same element twice.
8+
9+
Example:
10+
Given nums = [2, 7, 11, 15], target = 9,
11+
12+
Because nums[0] + nums[1] = 2 + 7 = 9,
13+
return [0, 1].
14+
15+
*/
16+
17+
/*
18+
作者知乎:https://www.zhihu.com/people/bing-mo-43-95/activities
19+
20+
解析:
21+
22+
题目的意思就是,找出两个数,使得这两个加起来等于给定数字。只有一组这样的解,同时不能使用同一个元素两次。
23+
24+
一种解法是暴力搜索,这个都会,不赞成使用。
25+
26+
第二种方法思路:
27+
与暴力方法不同,当我线性扫描数组时,如果能在O(1)的时间内找到,target-nums 的位置,那么就可以在O(n)的时间内找到,target-nums
28+
解决问题。这就需要使用Map函数。(它可以通过键来找值,在O(1)的时间即可)
29+
30+
算法流程:
31+
1.将数组里面的数据,通过键值对,来添加进Map中。
32+
2.线性扫描,两个数相加,则输出。由于唯一性,不必考虑过多。
33+
34+
35+
*/
36+
37+
class Solution {
38+
public int[] twoSum(int[] nums,int target) {
39+
Map<Integer,Integer> map=new HashMap<Integer,Integer>();
40+
//实现声明一个数组,结果返回给调用者。
41+
int[] result = new int[2];
42+
//将数组里面导入map中
43+
for(int i = 0 ;i<nums.length;i++){
44+
map.put(nums[i],i);
45+
}
46+
//线性扫描,找出合理的值
47+
for(int i = 0;i<nums.length;i++){
48+
49+
if(map.containsKey(target-nums[i])&&map.get(target-nums[i])!=i){
50+
51+
//判断两个元素,较小的排在前面,较大的在后面。
52+
if(i>map.get(target-nums[i])){
53+
result[0]=map.get(target-nums[i]);
54+
result[1]=i;
55+
}
56+
else{
57+
result[0]=i;
58+
result[1]=map.get(target-nums[i]);
59+
}
60+
break;
61+
}
62+
}
63+
64+
return result;
65+
66+
}
67+
}
68+
69+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /