每天一道算法题系列:
来源:力扣(LeetCode)
本题链接:https://leetcode-cn.com/problems/two-sum
来源是力扣,大家喜欢可以去力扣中文网做相应的其他的题,某浏览器直接搜力扣即可。
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
一般看到这样的问题,直接就是暴力解决办法,什么是暴力解决呢,其实说白了就是for循环,一个for循环解决不了的话,不要慌,肯定是for循环不够,再加一个就好。
/***
* 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
*
* 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
*
* 示例:
*
* 给定 nums = [2, 7, 11, 15], target = 9
*
* 因为 nums[0] + nums[1] = 2 + 7 = 9
* 所以返回 [0, 1]
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/two-sum
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
class Solution {
public static int[] twoSum(int[] nums, int target) {
for(int a=0 ; a<nums.length ;a++){
for(int b=a+1 ; b<nums.length ;b++){
if(a[j] == target - a[i]){
return new int[]{i,j};
}
}
}
//如果没有结果就报错
/**
* 这里有一个知识点,这里为什么不写Exception而要写IllegalArgumentException呢?
* 其实这里写Exception也没关系,在方法后面throws Exception抛出就好了
*/
throw new IllegalArgumentException("No two sum ");
}
public static void main(String[] args) {
//主方面随便定义一个数组a,把值传入到方法twoSum里面
int[] a ={1,2,56,54,123,13,5};
//for循环打印出两个满足条件的值
for (int c : twoSum(a, 14)){
System.out.println(c);
}
}
}
如有问题,请留言,会第一时间进行更正。
谢谢大家。