xxxxxxxxxx
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
start = 0
end = len(numbers) -1
while start < end:
tempSum = numbers[start] + numbers[end]
if tempSum == target:
return start+1, end+1
elif tempSum >= target:
end -= 1
else:
start +=1
xxxxxxxxxx
#Leetcode Two Sum in Javascript
var twoSum = function(numbs, target) {
let result = "";
if (result === "") {
for (let i = 0; i < numbs.length; i++) {
for (let j = 0; j < numbs.length; j++) {
if (i!== j) {
if (numbs[i] + numbs[j] === target) {
result=[j, i];
}
}
}
}
}
return result
};
xxxxxxxxxx
class Solution {
public int[] twoSum(int[] nums, int target) {
int arr[]= new int[2];
for(int i =0; i<nums.length; i++){
for(int j= i+1; j< nums.length; j++){
if(nums[i]+ nums[j]== target){
arr[0]= i;
arr[1] = j;
}
}
}
return arr;
}
}
xxxxxxxxxx
#Leetcode Two Sum in Python
class Solution(object):
def twoSum(self, arr, target):
final = []
for i in range(len(arr) - 1):
for j in range(i+1,len(arr)):
if arr[i] + arr[j] == target:
final.append(i)
final.append(j)
return final
xxxxxxxxxx
def twoSum(nums, target):
# Create a dictionary to store elements and their indices
num_dict = {}
# Iterate through the array
for i, num in enumerate(nums):
# Calculate the complement (the value needed to reach the target)
complement = target - num
# Check if the complement exists in the dictionary
if complement in num_dict:
# Return the indices of the current number and its complement
return [num_dict[complement], i]
# If the complement doesn't exist, add the current number and its index to the dictionary
num_dict[num] = i
# If no solution is found, return an empty list
return []
# Example usage
nums = [2, 7, 11, 15]
target = 9
result = twoSum(nums, target)
print(result) # Output: [0, 1] (nums[0] + nums[1] = 2 + 7 = 9)
xxxxxxxxxx
class Solution:
def twoSum(self, input: List[int], target: int) -> List[int]:
seen = []
for indvInput in range(0, len(input)):
remainder = target - input[indvInput]
if remainder in seen:
return (input.index(remainder),indvInput)
seen.append(input[indvInput])