forked from 0voice/interview_internal_reference
-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Update 1.3.5 给定一个整数数组和一个整数,返回两个数组的索引,这两个索引指向的数字的加和等于指定的整数。需要最优的算法,分析算…
…法的空间和时间复杂度.md
- Loading branch information
Showing
1 changed file
with
28 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
|
||
题目:给定一个整数数组和一个整数,返回两个数组的索引,这两个索引指向的数字的加和等于指定的整数。需要最优的算法,分析算法的空间和时间复杂度 | ||
|
||
参考答案: | ||
```Java | ||
public static int[] twoSum(int[] numbers, int target) { | ||
int i = 0, j = numbers.length - 1; | ||
|
||
while (i != j) { | ||
if (numbers[i] + numbers[j] == target) { | ||
return new int[]{i + 1, j + 1}; | ||
} | ||
|
||
if (numbers[i] + numbers[j] < target) { | ||
i++; | ||
continue; | ||
} | ||
|
||
if (numbers[i] + numbers[j] > target) { | ||
j--; | ||
continue; | ||
} | ||
} | ||
|
||
return new int[]{i, j}; | ||
} | ||
``` | ||
分析:空间复杂度和时间复杂度均为 O(n) |