twoSum Algorithm : How to improve this?

前端 未结 22 2126
礼貌的吻别
礼貌的吻别 2021-02-06 01:38

I felt like doing an algorithm and found this problem on leetcode

Given an array of integers, find two numbers such that they add up to a specific target num

22条回答
  •  北荒
    北荒 (楼主)
    2021-02-06 02:11

    Sort the array. Make two pointers point at first and last (x and X). Run this in a loop:

    if      (a[X]+a[x] >  N) then X-- 
    else if (a[X]+a[x] <  N) then x++
    else if (a[X]+a[x] == N) then found.
    
    if (x > X) then no numbers exist.
    

    O(nlogn) time, O(1) memory

提交回复
热议问题