Skip to content

Commit 7cccf8a

Browse files
authored
Add files via upload
1 parent 6080bcc commit 7cccf8a

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed

1、两数之和.md

+88
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
# 1、两数之和
2+
3+
给定一个整数数组 *nums* 和一个整数目标值 *target*,请你在该数组中找出 **和为目标值** *target* 的那 **两个** 整数,并返回它们的数组下标。
4+
5+
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
6+
7+
你可以按任意顺序返回答案。
8+
9+
10+
11+
**示例 1:**
12+
13+
```
14+
输入:nums = [2,7,11,15], target = 9
15+
输出:[0,1]
16+
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
17+
```
18+
19+
**示例 2:**
20+
21+
```
22+
输入:nums = [3,2,4], target = 6
23+
输出:[1,2]
24+
```
25+
26+
**示例 3:**
27+
28+
```
29+
输入:nums = [3,3], target = 6
30+
输出:[0,1]
31+
```
32+
33+
**提示:**
34+
35+
2 <= nums.length <= 104
36+
-109 <= nums[i] <= 109
37+
-109 <= target <= 109
38+
**只会存在一个有效答案**
39+
40+
来源:力扣(LeetCode)
41+
链接:https://leetcode-cn.com/problems/two-sum
42+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
43+
44+
**java实现**
45+
46+
```java
47+
class Solution {
48+
public int[] twoSum(int[] nums, int target) {
49+
int a[] = new int [2];
50+
for(int i = 0;i<nums.length;i++){
51+
for(int j = i+1;j<nums.length;j++){
52+
if(nums[i]+nums[j]==target){
53+
a[0] = i;
54+
a[1] = j;
55+
return a;
56+
}
57+
}
58+
}
59+
return a;
60+
}
61+
}
62+
```
63+
64+
c语言实现
65+
66+
```c
67+
/**
68+
* Note: The returned array must be malloced, assume caller calls free().
69+
*/
70+
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
71+
for(int i = 0;i<numsSize;i++){
72+
for(int j = i+1;j<numsSize;j++){
73+
if(nums[i]+nums[j]==target){
74+
int *ret = malloc(sizeof(int)*2);
75+
ret[0] = i;
76+
ret[1] = j;
77+
*returnSize = 2;
78+
return ret;
79+
80+
}
81+
}
82+
}
83+
*returnSize = 0;
84+
return NULL;
85+
86+
}
87+
```
88+

0 commit comments

Comments
 (0)