Value in simplicity?


  • 0
    D

    This is a O(n^2) solution correct? But is there not value in the simplicity and readability of the code? This seemed like the obvious answer to get the code running, but should I look to start with a more complex yet more efficient implementation from the get go? Feedback appreciated.

    This Solution's Runtime: 1000 ms | O(n) Solution Runtime: 412 ms

    public static int[] twoSum(int[] numbers, int target) {
        int[] indices = new int[2];
        
        for (int i = 0; i < numbers.length - 1; i++)
            for (int j = i + 1; j < numbers.length; j++)
                if (numbers[i] + numbers[j] == target) {
                    indices[0] = i + 1;
                    indices[1] = j + 1;
    
                    return indices;
                }
        
        return indices;
     }

Log in to reply
 

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