Code readability > performance?


  • 1
    C

    I favor code symmetry, which usually means better readability and less buggy.

    public class Solution {
        public List<List<Integer>> threeSum(int[] nums) {
            List<List<Integer>> result = new LinkedList<>();
            int len = nums.length;
            Arrays.sort(nums);
            for (int i = 0; i < len - 2; i++) {
                int sum1 = nums[i];
                if (sum1 > 0) break;
                if (i>0 && nums[i]==nums[i-1]) continue;
                for (int j = i + 1; j < len - 1; j++) {
                    int sum2 = sum1 + nums[j];
                    if (sum2 > 0) break;
                    if (j > i+1 && nums[j] == nums[j-1]) continue;
                    for (int k = j + 1; k < len; k++) {
                        int sum3 = sum2 + nums[k];
                        if (sum3 > 0) break;
                        if (k > j+1 && nums[k] == nums[k-1])continue;
    
                        if (sum3 == 0) result.add(Arrays.asList(nums[i], nums[j], nums[k]));
                    }
                }
            }
            return result;
        }
    }
    

    I think people usually tend to have more confidence on the code above, no worry about corner case.

    Pay attention to the "for => int => if => if"

    Easy to convince the reader that the code works.

    what do you think?


  • 0
    J

    I agree with readability.
    Everyone is removing white space and doing 1 line while loops. Makes it difficult to learn the thinking process.


  • 0
    P

    My code was really similar except I created a new list explicitly and added nums[i] to nums[k] line by line; that was considered to exceed the time limit o.O. Changing it to "result.add(Arrays.asList(nums[i], nums[j], nums[k]));" made it that much faster I guess!


Log in to reply
 

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