leetcode-----167. 两数之和 II - 输入有序数组
算法(暴力)
时间复杂度:\(O(n^2)\)
代码
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int n = numbers.size();
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
int t = numbers[i] + numbers[j];
if (t == target) return vector<int>{i + 1, j + 1};
if (t > target) break;
}
}
return vector<int>{};
}
};
算法(暴力)
时间复杂度:\(O(logn)\)
代码
class Solution {
public:
vector
int i = 0, j = numbers.size() - 1;
while (i < j) {
int t = numbers[i] + numbers[j];
if (t == target) return vector
if (t > target) j--;
if (t < target) i++;
}
return vector
}
};