Skip to content

Instantly share code, notes, and snippets.

@zeraf29
Created January 8, 2020 07:47
Show Gist options
  • Save zeraf29/396ee5c7e0e0079a24e3b5321136d376 to your computer and use it in GitHub Desktop.
Save zeraf29/396ee5c7e0e0079a24e3b5321136d376 to your computer and use it in GitHub Desktop.
Find value's indexes which each number's sum is same "sum" parameter value
static void twoSumValue(int[] nums, int sum) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i=0; i<nums.length; i++){
int target = sum - num[i];
if(map.containsKey(target)){
System.out.println((map.get(target)+" "+(i)));
break;
}
map.put(cost[i],i);
}
}
@zeraf29
Copy link
Author

zeraf29 commented Jan 8, 2020

Ex)
nums = [1,4,5,3,2]
sum = 4
answer : index 0 and 3 (each value are 1 and 3) values (index0 + index3 = 1+3 = 4 =sum)

*nums can have same values. for example, nums = [1,4,1,3]. In this case, return lowest index value.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment