Hashtable
Hashtable
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.
class Solution {
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 };
}
}
}
return new int[]{};
}
}
Approach 2|Two-pass HashTable
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> hm = new HashMap<>();
for(int i = 0; i < nums.length; i++)
{
hm.put(nums[i],i);
}
for(int i = 0; i < nums.length; i++){
if(hm.containsKey(target-nums[i]) && hm.get(target-nums[i])!=i)
{
return new int[]{hm.get(target-nums[i]),i};
}
}
return new int[]{};
}
}
Approach 3|One-pass HashTable|Best Approach:
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target-nums[i])) {
return new int[] { map.get(target-nums[i]), i };
}
map.put(nums[i], i);
}
return new int[]{};
}
}
Longest substring without repeating characters
Given a string s, find the length of the longest substring without repeating characters.