twoSum Algorithm : How to improve this?

前端 未结 22 2375
礼貌的吻别
礼貌的吻别 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: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;
    }
    

提交回复
热议问题