题目
两数之和 https://leetcode-cn.com/problems/two-sum/submissions/
解答结果
执行用时:45 ms, 在所有 Java 提交中击败了38.35% 的用户
内存消耗:41.1 MB, 在所有 Java 提交中击败了42.24% 的用户
通过测试用例:57 / 57
代码
package leetcode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.IntStream;
/**
* @Author 夏秋初
* @Date 2022/3/7 22:54
*/
class Solution {
public static void main(String[] args) {
int count;
int[] array;
int target;
//
Scanner scanner = new Scanner(System.in);
System.out.print("请输入数组大小:");
int num = scanner.nextInt();
array = new int[num];
//
System.out.print("请输入数组元素:");
for (int i = 0; i < num; i++) {
array[i] = scanner.nextInt();
}
System.out.print("请输入两数之和:");
target = scanner.nextInt();
new Solution().twoSum(array, target);
}
public int[] twoSum(int[] nums, int target) {
// for (int i = 0; i < nums.length; i++) {
// for (int j = i; j < nums.length; j++) {
// if(target == nums[i] + nums[j] && i != j){
// return new int[]{i, j};
// }
// }
// }
// return null;
for (int i = 0; i < nums.length; i++) {
int res = target - nums[i];
for (int j = i; j < nums.length; j++) {
if (nums[j] == res && i != j) {
return new int[]{i, j};
}
}
}
return null;
}
}