2021-01-19
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
题目描述:
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
算法思想:
使用双指针,一个指针指向值较小的元素,一个指针指向值较大的元素。指向较小元素的指针从头向尾遍历,指向较大元素的指针从尾向头遍历。
如果两个指针指向元素的和 sum == target,那么得到要求的结果;
如果 sum > target,移动较大的元素,使 sum 变小一些;
如果 sum < target,移动较小的元素,使 sum 变大一些。
数组中的元素最多遍历一次,时间复杂度为 O(N)。只使用了两个额外变量,空间复杂度为 O(1)。
自我总结:
- 创建新的数组 - Define and initialise new arrays:
- Using new
int[] result = new int[10];
String[] diff = new String[10];
When you create an array object using new, all its slots are initialised for you (0 for numeric arrays, false for boolean, '\0' for character arrays, and null for objects). You can then assign actual values or objects to the slots in that array.
- Create an array and initialise its contents at the same time. Instead of using new to create the new array object, enclose the elements of the array inside braces, separated by commas:
String[] chiles = { "jalapeno", "anaheim", "serrano",
"habanero", "thai" };
本题目里需要创建类型为数组的返回值:
方法1:
return new int[] {i+1, j+1};
方法2:
int[] result = {i+1, j+1};
return result; #此种方法会占用更多内存
- 注意返回的地方未必是循环外(程序结尾)
- 循环条件如何限定