Python, O(nlogn), 46ms


  • 0
    O
    def twoSum(self, nums, target):
            def _get_ans(values):
                ans = [-1, -1]
                for index, num in enumerate(nums):
                    if ans[0] == -1 and num == values[0]:
                        ans[0] = index
                    if num == values[1]:
                        ans[1] = index
                return ans
        
            ordered_nums = sorted(nums)
            ans = [0, len(ordered_nums) - 1]
            while ans[0] < ans[1]:
                if ordered_nums[ans[0]] + ordered_nums[ans[1]] == target:
                    return _get_ans([ordered_nums[index] for index in ans])
                if ordered_nums[ans[0]] + ordered_nums[ans[1]] > target:
                    ans[1] -= 1
                if ordered_nums[ans[0]] + ordered_nums[ans[1]] < target:
                    ans[0] += 1
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.