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 twoSum(vector& numbers, int target) {
int i = 0, j = numbers.size() - 1;
while (i < j) {
int t = numbers[i] + numbers[j];
if (t == target) return vector{i + 1, j + 1};
if (t > target) j--;
if (t < target) i++;
}
return vector{};
}
};

posted @ 2020-03-23 15:17  景云ⁿ  阅读(143)  评论(0编辑  收藏  举报