twoSum Algorithm : How to improve this?

前端 未结 22 2098
礼貌的吻别
礼貌的吻别 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:13
    1. Sort the list in non-decreasing order. It takes O(nlogn) time complexity.
    2. Find the two numbers, which can be done in O(n) time.
    3. Find the two indices of the two numbers, which can be done in O(n) time.

    Overall complexity is O(nlogn).

    Implementation in python:

    class Solution:
      def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        p = nums[:]
        p.sort() #sorting in -> O(nlogn)
        r = len(nums)-1
        l =0 
    
        #find the indices -> O(n)
        for i in range(len(nums)):
          if(p[l] + p[r]<target): 
            l += 1
          elif (p[l] + p[r]>target): 
            r -=1
          else :
            first_num = p[l]
            second_num = p[r]
    
        #find the indices of the numbers -> O(n)
        for i in range(len(nums)):
          if(nums[i]==first_num):
            first_index = i
          elif (nums[i]==second_num):
            second_index = i
        return [first_index,second_index]
    
    0 讨论(0)
  • 2021-02-06 02:14

    One line solution in python :

    class Solution(object):
        """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
        """
        def twoSum(self, nums, target):            
            x = [[i, nums.index(target-j)] for i,j in enumerate(nums) if nums.count(target-j) > 0 and nums.index(target-j)!=i]
    
            return x.pop()
    
    0 讨论(0)
  • 2021-02-06 02:14

    Here is an O(n):

    public int[] findSumMatched(int[] numbers, int target) {
        Map<Integer, Integer> mapOfNumbers = new HashMap<Integer, Integer>();
        for (int i = 0; i<numbers.length; i++) {
            int secondNumber = target - numbers[i];
            if (mapOfNumbers.get(secondNumber) != null){
                return new int[] {mapOfNumbers.get(secondNumber), i};
            }
            mapOfNumbers.put(numbers[i], i);
        }
        throw new IllegalArgumentException();
    }
    
    0 讨论(0)
  • 2021-02-06 02:15

    Just curious, but what's wrong with this O(n) solution?

    public int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length - 1; i++){
            if (nums[i] + nums[i+1] == target)
                return new int[] {i, i+1};
        }
        return null;
    }
    
    0 讨论(0)
提交回复
热议问题