Skip to content

Commit

Permalink
Update 1.3.5 给定一个整数数组和一个整数,返回两个数组的索引,这两个索引指向的数字的加和等于指定的整数。需要最优的算法,分析算…
Browse files Browse the repository at this point in the history
…法的空间和时间复杂度.md
  • Loading branch information
ArtarisCN authored Jul 15, 2019
1 parent b21e237 commit ca87327
Showing 1 changed file with 28 additions and 0 deletions.
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)

0 comments on commit ca87327

Please sign in to comment.