标签:一个 break value i++ 出差 table alt keyword 整数
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9,所以返回 [0, 1]
根据题意,数组中一定会有一个答案,于是我首先想到的是用目标值target减去数组nums中的某个数得出差值,再到数组剩下的数中查找等于差值的数即可。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
class Solution { public int[] twoSum(int[] nums, int target) { int res[] = new int[]{0,1}; int index = -1; for (int i = 0; i < nums.length; i++) { int diff = target - nums[i]; for (int j = i + 1; j < nums.length; j++) { if (nums[j] == diff) { index = j; break; } } if (index > -1) { res[0] = i; res[1] = index; break; } } return res; }} |
执行结果:通过
标签:一个 break value i++ 出差 table alt keyword 整数
原文地址:https://www.cnblogs.com/keepfriend/p/14491782.html