Two Sum Problem - Code
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
For example
if target = 8
array = [1, 2, 5, 6]
then it should return {1, 3}
In JAVA
Brute Force
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] == target - nums[i]) {
return new int[] { i, j };
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
*returnSize = 2;
int *array = (int*)malloc((*returnSize)*sizeof(int));
for(int i=0; i<numsSize; i++){
for(int j= i+1; j<numsSize; j++){
if(nums[i]+nums[j]==target){
array[0]=i;
array[1]=j;
}
}
}
return array;
}
In Python Language