C++20 Ranges: Two Sum Solution with enumerate and adjacent_pairs

This article presents a C++20 solution for the classic Two Sum problem, leveraging the power of range-v3 library's enumerate and adjacent_pairs functions.

Problem Statement:

Given an array of integers nums and an integer target, find the indices of the two numbers in nums that add up to target. You can assume that each input will have exactly one solution, and the same element cannot be used twice.

Solution using C++20 Ranges:

Since the problem requires returning indices, we need to track the index of each element. The enumerate function from the range-v3 library comes in handy. It pairs each element with its corresponding index, creating a range of pairs.

Here's the breakdown of the solution:

  1. Transform the array into a range: Use views::all(nums) to create a range from the input vector nums.
  2. Pair elements with indices: Apply views::enumerate to associate each element with its index.
  3. Get adjacent pairs: Use views::adjacent_pairs to obtain pairs of consecutive elements from the enumerated range.
  4. Find the target pair: Utilize find_if to search for a pair where the sum of the elements equals the target.
  5. Retrieve indices: If a matching pair is found, extract its indices and return them as a vector.

Code:

#include <iostream>
#include <vector>
#include <range/v3/all.hpp>

using namespace ranges;

class Solution {
public:
    std::vector<int> twoSum(std::vector<int>& nums, int target) {
        auto pairs = views::all(nums) | views::enumerate | views::adjacent_pairs;
        auto it = find_if(pairs, [=](auto p) { return p.first + p.second == target; });
        if (it != pairs.end()) {
            return {it->first, it->first + 1};
        }
        return {};
    }
};

int main() {
    std::vector<int> nums{2, 7, 11, 15};
    int target = 9;
    Solution s;
    auto result = s.twoSum(nums, target);
    std::cout << "[" << result[0] << ", " << result[1] << "]" << std::endl;
    return 0;
}

Explanation:

  • The code starts by including the necessary headers and using the ranges namespace.
  • The Solution class encapsulates the twoSum function, which takes the input vector nums and the target value as arguments.
  • Inside twoSum, we create a range of pairs using views::all, views::enumerate, and views::adjacent_pairs as explained earlier.
  • We then use find_if to search for a pair whose sum equals target.
  • If a matching pair is found, its indices (it->first and it->first + 1) are returned as a vector. Otherwise, an empty vector is returned.

This C++20 range-based solution provides a clean and expressive way to solve the Two Sum problem. By leveraging the enumerate and adjacent_pairs functions, we efficiently identify the required indices without resorting to traditional loops or iterators. This approach showcases the elegance and conciseness of C++20 ranges, making code more readable and maintainable.

C++20 Ranges: Two Sum Solution with enumerate and adjacent_pairs

原文地址: https://www.cveoy.top/t/topic/lEWb 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录