Two Pointer Flashcards
1
Q
Two Sum UnSorted / Sorted
A
public class Solution { public int[] twoSum(int[] nums, int target) { Map map = new HashMap<>(); int[] res = new int[2]; for (int i = 0;i target) right--; if (sum < target) left++; } return res; } }
2
Q
3 Sum adding up to 0
A
class Solution { public List> threeSum(int[] nums) { List> result = new ArrayList<>(); if (nums == null || nums.length < 3){ return result; }
Arrays.sort(nums); for (int i = 0;i= 0 && nums[i] == nums[i-1]) continue; int left = i+1; int right = nums.length-1; while (left < right){ int sum = nums[i] + nums[left] + nums[right]; if (sum == 0){ result.add(Arrays.asList(nums[i], nums[left], nums[right])); while (left + 1 < right && nums[left] == nums[left+1]) left++; while (left < right-1 && nums[right] == nums[right-1]) right--; left++; right--; } else if (sum < 0) left++; else right--; } } return result; } }