Advertisement
exmkg

Untitled

Aug 23rd, 2024
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.43 KB | None | 0 0
  1. class Solution {
  2.     public int[] twoSum(int[] nums, int target) {
  3.         //          i=5
  4.         // [..., nums[i] = 17, ...]
  5.         // target = 77
  6.         // lastSeenSoFar = { 22: 0, 61: 1, 23: 4, 56: 3, 12: 2 }
  7.         // lastSeenSoFar.containsKey(77 - 17, i.e. 60) -> false
  8.         // No problem, let's record -> lastSeenSoFar.put(17, 5) // key=17 (number), value=5 (lastSeenIndex)
  9.         // lastSeenSoFar = { 22: 0, 61: 1, 23: 4, 56: 3, 12: 2, 17: 5}
  10.        
  11.         //          i=6
  12.         // [..., nums[i] = 21, ...]
  13.         // target = 77
  14.         // lastSeenSoFar = { 22: 0, 61: 1, 23: 4, **56: 3**, 12: 2, 17: 5}
  15.         // lastSeenSoFar.containsKey(77 - 21, i.e. 56) -> true
  16.         // Cool! Return {lastSeenSoFar.get(56) [i.e. 3], i [i.e. 6]}
  17.  
  18.         // Map<Number, IndexLastSeen>
  19.         Map<Integer, Integer> lastSeenSoFar = new HashMap<>();
  20.         for (int i = 0; i < nums.length; ++i) {
  21.             int b = nums[i];
  22.             int a = target - b;
  23.             if (lastSeenSoFar.containsKey(a)) {
  24.                 // Found pair of (a, b), so that a + b = target
  25.                 // Number a last seen at index lastSeenSoFar.get(a)
  26.                 // and number b is last seen at index i.
  27.                 return new int[]{lastSeenSoFar.get(a), i};
  28.             }
  29.             // Save that number b (nums[i]) last seen at index i.
  30.             lastSeenSoFar.put(b, i);
  31.         }
  32.         return new int[]{};
  33.     }
  34. }
  35.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement