twoSum Algorithm : How to improve this?

前端 未结 22 2093
礼貌的吻别
礼貌的吻别 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:01

    I would approach it this way:

    1. Order your array from smaller to lower value

    2. Loop over your array the way you have it but exit the loop early whenever

      target <(numbers[i]+numbers[j])

    3. Once you have the value of your two elements such that n[0] + n[1] = target, look back at the original array to find their index.

提交回复
热议问题