You can create a Python class to find a pair of elements in an array whose sum equals a specific target number using a dictionary to keep track of the elements you've seen so far. Here's a sample implementation:
```python
class TwoSumFinder:
def __init__(self,numbers,target):
self.numbers = numbers
self.target = target
self.indices = {}
def find_indices(self):
for i, num in enumerate(numbers):
complement = target - num
if complement in self.indices:
return [self.indices[complement], i]
self.indices[num] = i
return None
# Example usage
if __name__ == "__main__":
numbers = [10, 20, 10, 40, 50, 60, 70]
target = 50
finder = TwoSumFinder(numbers,target)
result = finder.find_indices()
if result:
print(f"Output: {result[0]}, {result[1]}")
else:
print("No pair found with the given target sum.")
```
In this code, we define a `TwoSumFinder` class with an `__init__` method to initialize array (`self.numbers`), target number(`self.target`) and an empty dictionary (`self.indices`). The `find_indices` method iterates through the elements of `numbers` list. For each element, it calculates the complement needed to reach the target sum and checks if that complement exists in the dictionary. If it does, it returns the indices of the two elements that add up to the target sum. If no such pair is found, it returns `None`.
The example usage at the end demonstrates how to create an instance of the `TwoSumFinder` class and use it to find the indices of the pair of elements that add up to the target sum. In this case, it would print "Output: 3, 4" as specified in your example input and output.
Additionaly, there are also some alternative functions which provides same functionality.
* Method 1: Brute Force (Nested Loop)
```python
def find_indices_bruteforce(numbers, target):
n = len(numbers)
for i in range(n):
for j in range(i+1, n):
if numbers[i] + numbers[j] == target:
return [i, j]
return None
```
This method uses a nested loop to compare each pair of elements in the array. It has a time complexity of O(n^2).
* Method 2: Sorting and Two Pointers
```python
def find_indices_sorted(numbers, target):
sorted_numbers = sorted(enumerate(numbers), key=lambda x: x[1])
left, right = 0, len(numbers) - 1
while left < right:
current_sum = sorted_numbers[left][1] + sorted_numbers[right][1]
if current_sum == target:
return [sorted_numbers[left][0], sorted_numbers[right][0]]
elif current_sum < target:
left += 1
else:
right -= 1
return None
```
This method involves sorting the array and then using two pointers to find the pair. It has a time complexity of O(n log n) due to the sorting step.
* Method 3: Using a Set
```python
def find_indices_set(numbers, target):
seen = {}
for i, num in enumerate(numbers):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return None
```
This method is similar to the dictionary-based approach but uses a set to store the seen elements. It has a time complexity of O(n).