两数之和

int twoSum(const int nums[], const int n, const int target, std::vector<int>& result)
{
    result.clear();
    if (n < 2) return -1;

    const int* left, * right;
    left = nums;
    right = nums + n - 1;

    while (left < right)
    {
        const int sum = (*left + *right);
        if (sum == target)
        {
            result.push_back(left - nums);
            result.push_back(right - nums);
            return 0;
        }
        if (sum < target) left++;
        else right--;
    }

    return -1;
}


int twoSumV2(const int nums[], const int n, const int target, std::vector<int>& result)
{
    result.clear();
    if (n < 2) return -1;

    for (int i = 0; i < n - 1; i++)
    {
        for (int j = i + 1; j < n; j++)
        {
            const int sum = nums[i] + nums[j];
            if (sum == target)
            {
                result.push_back(i);
                result.push_back(j);
                return 0;
            }
        }
    }

    return -1;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务