package com.cheng.leetcode;
/**
* @author c
* @create 2020-12-21 19:01
* 1. 两数之和
* 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
* 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
*
* 示例:
* 给定 nums = [2, 7, 11, 15], target = 9
* 因为 nums[0] + nums[1] = 2 + 7 = 9
* 所以返回 [0, 1]
* 通过次数1,627,092提交次数3,279,092
*
*本方法使用暴力求解
*/
public class Demo0001 {
public int[] twoSum(int[] nums, int target) {
//定义结果集
int[] result = new int[2];
//判断是否成立的变量
boolean flag = false;
//遍历数组
for (int i = 0; i < nums.length; i++) {
result[0] = i;
for (int j = 0; j < nums.length; j++) {
if (nums[j]+nums[i] == target && j != i) {
result[1] = j;
flag = true;
break;
}
}
//判断本次结果是否成立
if (flag) {
break;
}
}
return result;
}
public static void main(String[] args) {
int[] result = new Demo0001().twoSum(new int[]{-1, -2, -3, -4, -5}, -8);
for (int i : result) {
System.out.println(i);
}
}
}
LeetCode1. 两数之和
最新推荐文章于 2024-07-25 21:13:04 发布