LeetCode编程练习 - Two Sum学习心得

题目:

       Given an array of integers, return indices of the two numbers such that they add up to a specific target.

       You may assume that each input would have exactly one solution, and you may not use thesame element twice.

       Example:

       Given nums = [2, 7, 11, 15], target = 9,

    Because nums[0] + nums[1] = 2 + 7 = 9,

    return [0,1].
 

思路:

        定义两个变量,用来索引数组中的数值,然后判断索引的数值是否满足条件,若满足则输出索引值。在返回索引值时需要定义一个新的数组来装载输出的索引值,应为return new int[] {i,j}。在索引第二个数值时我为其赋值为0 ,即int j = 0,但解决方案中赋值为i + 1,也就是说索引的第二个值是只能是前面索引值之后的数值,按照我输出的程序执行,数组为[1,2,3,4],当我确定一个具体值为4时,程序索引值为[0,2],而不显示[1,1],若我将数组中的[3]删除,程序索引值显示[0,0],显示出现错误,也就是说程序并没有遍历所有值。题目中说“每个输入只有一个解决方案”,可能就是这个意思,刚开始并没有读懂这句话的意思。执行程序后,显示错误“不是所有代码分支都有返回值”,由于如果for条件不满足就无法执行return,添加语句若不满足条件就返回数组。


代码:

       出现错误的代码:

    LeetCode编程练习 - Two Sum学习心得

     

        更改后的代码:

 LeetCode编程练习 - Two Sum学习心得