DEV Community

duccanhole
duccanhole

Posted on

code every day with me

--DAY 20--

Hi, I am going to make #100DaysOfCode Challenge. Everyday I will try solve 1 problem from leetcode or hackerrank. Hope you can go with me until end.
Now let's solve problem today:
Problem: Two Sum II
Detail: here
My solution(javascript):

var twoSum = function(numbers, target) {
    let i=0,j=numbers.length-1;
    while(i<j){
        if(numbers[i]+numbers[j]==target){
            return [i+1,j+1];
        }
        else if (numbers[i] + numbers[j] < target)
            i++;
        else
            j--;
    }
};
Enter fullscreen mode Exit fullscreen mode

-->If you have better solution or any question, please comment below. I will appreciate.

Top comments (5)

Collapse
 
korzo profile image
korzo

You should cache the addition.
I ended up with this solution, but apparently it's slower (as long as runtime is reliable).

var twoSum = function(numbers, target) {
    let i = 0, j = numbers.length - 1, sum;

    while ((sum = numbers[i] + numbers[j]) !== target) {
        sum > target ? j-- : i++;
    }

    return [i + 1, j + 1];
};
Enter fullscreen mode Exit fullscreen mode
Collapse
 
namhle profile image
Nam Hoang Le

It would be more nicer if the solution has highlighted code and some comments about it (complexity for example).

Collapse
 
coderduck profile image
duccanhole

thanks, but can you show me how to do that?

Collapse
 
namhle profile image
Nam Hoang Le • Edited

By wrapping your code like this

dev-to-uploads.s3.amazonaws.com/up...

Formatting your code with some tools like prettier is even better 👌🏻

Thread Thread
 
coderduck profile image
duccanhole

thank u so much !