C++20 Ranges: Two Sum Solution with enumerate and adjacent_pairs
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:
- Transform the array into a range: Use
views::all(nums)to create a range from the input vectornums. - Pair elements with indices: Apply
views::enumerateto associate each element with its index. - Get adjacent pairs: Use
views::adjacent_pairsto obtain pairs of consecutive elements from the enumerated range. - Find the target pair: Utilize
find_ifto search for a pair where the sum of the elements equals thetarget. - 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
rangesnamespace. - The
Solutionclass encapsulates thetwoSumfunction, which takes the input vectornumsand the target value as arguments. - Inside
twoSum, we create a range of pairs usingviews::all,views::enumerate, andviews::adjacent_pairsas explained earlier. - We then use
find_ifto search for a pair whose sum equalstarget. - If a matching pair is found, its indices (
it->firstandit->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.
原文地址: https://www.cveoy.top/t/topic/lEWb 著作权归作者所有。请勿转载和采集!