1. Two Sum
O(n
2)
class Solution {
public int[] twoSum(int[] nums, int target) {
int [] results = new int[2];
for(int i = 0; i < nums.length-1; i++)
{
for(int j = i+1; j < nums.length; j++)
if(target == (nums[i]+nums[j]))
{
results[0] = i;
results[1] = j;
}
}
return results;
}
}
O(n)
class Solution {
public int[] twoSum(int[] nums, int target) {
int [] results = new int[2];
HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
for(int i = 0; i < nums.length; i++)
{
if(m.containsKey(nums[i]))
{
results[0] = i;
results[1] = m.get(nums[i]);
break;
}
else{
m.put((target-nums[i]), i);
}
}
return results;
}
}