剑指offer——面试题41-2:和为S的两个数字

力扣

双指针算法

Python

class Solution:
    def twoSum(self, price: List[int], target: int) -> List[int]:
        if len(price) < 2:
            return []
        l, r = 0, len(price) - 1
        while l < r:
            if price[l] + price[r] == target:
                return [price[l], price[r]]
            elif price[l] + price[r] < target:
                l += 1
            else:
                r -= 1
        return []

Java

class Solution {
    public int[] twoSum(int[] price, int target) {
        int left = 0, right = price.length - 1;
        while (price[left] + price[right] != target) {
            if (price[left] + price[right] > target) {
                right--;
            } else {
                left++;
            }
        }
        return new int[]{price[left], price[right]};
    }
}

##Solution1:
算法:双指针的经典用法

class Solution {
public:
    vector<int> FindNumbersWithSum(vector<int> array,int sum) {
        int low = 0, high = array.size() - 1;
        vector<int> res;
        while(low < high){
            if(array[low] + array[high] > sum)
                high--;
            else if(array[low] + array[high] < sum)
                low++;
            else {
                if(res.size() == 2 && array[low] * array[high] < res[0] * res[1]) {
                    res[0] = array[low];
                    res[1] = array[high];
                }
                if(res.size() == 0) {
                    res.push_back(array[low]);
                    res.push_back(array[high]);
                }
                low++;
            }
        }
        return res;
    }
};

##Solution2:
20180906重做

class Solution { // 双指针算法
public:
    vector<int> FindNumbersWithSum(vector<int> array,int sum) {
        if (array.size() < 2) return {};
        if (array.size() == 2) {
            if (array[0] + array[1] == sum)
                return array;
            else return {};
        }
        vector<int> res(2, 0);
        int multi_res = INT_MAX;
        int left = 0, right = array.size() - 1;
        while (left < right) {
            if (array[left] + array[right] < sum)
                left++;
            else if (array[left] + array[right] > sum)
                right--;
            else { // 和恰好为sum
                if (array[left] * array[right] < multi_res) {
                    multi_res = array[left] * array[right];
                    res[0] = array[left];
                    res[1] = array[right];
                }
                left++; right--;
            }
        }
        if (!res[0] && !res[1])
            return {};
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值