Python code difference ?


  • -1
    J

    This is my current solution

    Solution 1

    class Solution(object):
    def removeElement(self, nums, val):
        count = 0
        for k in nums:
            if k != val:
                nums[count] = k
                count += 1
        return count
    

    Solution 2

    class Solution(object):
    def removeElement(self, nums, val):
        count = 0
        for k in nums:
            if k != val:
                count += 1
        return count
    

    how is solution1 any different from solution2 since i am returning only count.


  • 0

    You don't just return something. The first one also modifies the given list, just like it should.


  • 0
    J

    Yes thats correct but why is the value of count different in these two solutions if the input is [4,5] and 4


  • 0

    No idea what you're talking about. Both solutions return count = 1.


  • 0
    J

    when the input is [4,5] 4 the output for the first solution is 5 but for the second solution it is 4


  • 0

    No, it's not 5 and 4. It's [5] and [4]. And it's not the count but the list (or rather a prefix of it).


Log in to reply
 

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