Why is Swift solution so much slower?


  • 0

    Java

    Runs in 11ms

    public int findMaxConsecutiveOnes(int[] nums) {
            int count = 0, max_count = 0;
            
            for (int e: nums) {
                if (e == 1) {
                    count++;
                    max_count = Math.max(count, max_count);
                } else {
                    count = 0;
                }    
            }
            
            return max_count;
        }
    

    Swift

    Runs in 72 ms!

    func findMaxConsecutiveOnes(_ nums: [Int]) -> Int {
            var count = 0
            var maxCount = 0
            for i in nums {
                if i == 1 { 
                    count = count + 1
                    maxCount = max(maxCount, count)
                } else {
                    count = 0
                } 
            }
            return maxCount
        }
    

Log in to reply
 

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