Thursday, August 17, 2017

LeetCode - 1. Two Sum

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) 

No comments:

Post a Comment

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 ...