Source Link:
https://leetcode.com/problems/two-sum/description/
Question:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
My Solution:
Note:
1. Using HashMap:
HashMap<Integer,Integer> hashmap = new HashMap<Integer,Integer>();
2. Put the number as "key", and its index as "value"
hashmap.put(nums[i], i);
3. We are looking for another number that is equal to "target - nums[i]"
int another = target - nums[i];
4. if we can find another_number and another_number is not itself
if(hashmap.containsKey(another) && (int)hashmap.get(another) !=i)
Subscribe to:
Post Comments (Atom)
Codility - Lesson 16 Greedy algorithms - 2. MaxNonoverlappingSegments
Source Link: https://app.codility.com/programmers/lessons/16-greedy_algorithms/max_nonoverlapping_segments/ Question: Located on a line ...
-
Source Link: https://app.codility.com/programmers/lessons/15-caterpillar_method/count_distinct_slices/ Question: An integer M and a...
-
Source Link: https://app.codility.com/programmers/lessons/15-caterpillar_method/count_triangles/ Question: A zero-indexed array A consi...
-
Source Link: https://codility.com/programmers/lessons/9-maximum_slice_problem/max_slice_sum/ Question: A non-empty zero-indexed array A...
No comments:
Post a Comment