1 분 소요

Link

class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        # At first, two pointer is used for making 'O(n^2)'(if using two for loof...) to 'O(N)'
        # This is line for normal setting of 'two pointer'.
        # I think that's just convention when you solve this kind of problem.
        i, j =0, len(numbers)-1 

        # only using 'while loof' of O(N) is much better than using 'adding conditional statesment in that while loof for checking'
        # we just need to moving two pointers until finding target.
        while numbers[i] + numbers[j] != target:
            s = numbers[i] + numbers[j]

            # That's just typical condition for checking all the elements
            # of the list.      
            if s > target: 
              
              # By that we can move 'i' index and 'j' index.
                j -= 1
            else:
                i += 1 
                
        return [i + 1 , j + 1]

Summary

1.At first, two pointer is used for making ‘O(n^2)’(if using two for loop…) to ‘O(N)’.

i, j =0, len(numbers)-1 

This is line for normal setting of ‘two pointer’. I think that’s just convention when you solve this kind of problem.

  1. That’s just typical condition for checking all the elements of the list. By that, we can move ‘i’ index and ‘j’ index.
         while numbers[i] + numbers[j] != target:
             s = numbers[i] + numbers[j]        
             if s > target: 
                 j -= 1
             else:
                 i += 1 
    

댓글남기기