DEV Community

schudy
schudy

Posted on

LeetCode 167. Two Sum II - Input array is sorted

I used two ways to solve this problem.

  1. Define a dictionary dic, traverse numbers to see if target - number in dic. If it is, then return the two indices array (sorted), else store the number in dic for further matching.
    Alt Text

  2. Use two pointers. l starts from 0 and r starts from the last. If target - numbers[l] = numbers [r], then return array [l + 1, r + 1]; else if the sum is bigger than target, move r left, if is smaller than target, move l rightward, until they find the target sum.
    Alt Text

Top comments (0)