is there any problem with my code


  • 0
    G

    the output of my code is correct, but I saw someone's code is much longer than mine. so I'm wondering what the problem of my code?

    public class Solution {
        public int[] twoSum(int[] nums, int target) {
            int[] res=new int[2];
            for(int i=0;i<nums.length;i++){
                for(int j=i+1;j<nums.length;j++){
                    if (nums[i]+nums[j]==target){
                    res[0]=i;
                    res[1]=j;
                    break;
                }
            }
            }
            return res;
        }
    }
    

  • 0
    E

    @gavin1818 Your code is O(n^2). There are better ways of solving this problem:

    1. O(nlogn) -- sorting the array
    2. O(n) with extra space using hash table.

  • 0
    G

    @envySoft I see, thanks.


Log in to reply
 

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