twoSum Algorithm : How to improve this?

前端 未结 22 2117
礼貌的吻别
礼貌的吻别 2021-02-06 01:38

I felt like doing an algorithm and found this problem on leetcode

Given an array of integers, find two numbers such that they add up to a specific target num

22条回答
  •  忘了有多久
    2021-02-06 02:03

    Here is my cpp solution with O(nlog(n)):

    vector two_sum(vector &numbers, int target) {
        vector result;
        vector numbers_dup = vector(numbers);
    
        sort(numbers_dup.begin(), numbers_dup.end());
    
        int left = 0, right = numbers_dup.size() - 1;
        while(left <= right) {
            int sum = numbers_dup[left] + numbers_dup[right];
    
            if(sum == target) {
                //find the idex of numbers_dup[left] and numbers_dup[right]
                for(int i = 0; i < numbers.size(); i++) {
                    if(numbers[i] == numbers_dup[left] || numbers[i] == numbers_dup[right]) {
                        result.push_back(i);
                    }
                    if(result.size() == 2) {
                        return result;
                    }
                }
            }
            else if(sum > target) {
                right--;
            }
            else {
                left++;
            }
        }
    }
    

    Check out my blog for the detailed explanation. https://algorithm.pingzhang.io/Array/two_sum_problem.html

提交回复
热议问题