今天在leetcode上完成这道题目时:

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

初步代码为

 1 class Solution {
 2     public int[] twoSum(int[] nums, int target) {
 3         for (int i = 0; i < nums.length; i++) {
 4             for (int j = i + 1; j < nums.length-i-1; j++) {
 5                 if (nums[j] == target - nums[i]) {
 6                    return new int[] {i,j};
 7                 }
 8             }
 9         }
10         throw new IllegalArgumentException("No two sum solution");
11     }
12     public static void main(String args[]){
13         int []num=new int[]{3,6,8,11,15};
14         Solution s=new Solution();
15         System.out.println("数组下标为"+s.twoSum(num, 9));
16     }
17 }

运行后结果为

 后上网搜索原因,有如下解释

[代表是数组,几个就代表几维

I代表是int类型

@是固定的

7852e922代表的是数组的地址值

是动态初始化后数组对象打印的格式;

寻找解决方法时搜索出来这条网址:https://blog.csdn.net/qq_33343480/article/details/53784202

尝试着将System.out.println("数组下标为"+s.twoSum(num, 9));

改为       System.out.println("数组下标为"+Arrays.toString(s.twoSum(num, 9)));

后结果为

 但是该方法有一点瑕疵,就是只能算出一对元素来,如果数组元素是{3,6,8,1,12},返回的元素仍然是[0,1],而不是[0,1,2,3],本人关于两数之和的算法还不够好,仍需探索

01-14 05:55