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.
算法思想:
使用雙指針白翻,一個(gè)指針指向值較小的元素遮斥,一個(gè)指針指向值較大的元素籍凝。指向較小元素的指針從頭向尾遍歷,指向較大元素的指針從尾向頭遍歷究履。
如果兩個(gè)指針指向元素的和 sum == target,那么得到要求的結(jié)果埠褪;
如果 sum > target切端,移動(dòng)較大的元素,使 sum 變小一些寂祥;
如果 sum < target荐虐,移動(dòng)較小的元素,使 sum 變大一些壤靶。
數(shù)組中的元素最多遍歷一次缚俏,時(shí)間復(fù)雜度為 O(N)。只使用了兩個(gè)額外變量贮乳,空間復(fù)雜度為 O(1)。
自我總結(jié):
- 創(chuàng)建新的數(shù)組 - 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" };
本題目里需要?jiǎng)?chuàng)建類型為數(shù)組的返回值:
方法1:
return new int[] {i+1, j+1};
方法2:
int[] result = {i+1, j+1};
return result; #此種方法會(huì)占用更多內(nèi)存
- 注意返回的地方未必是循環(huán)外(程序結(jié)尾)
- 循環(huán)條件如何限定