Leetcode Python问题

2024-04-20 12:04:58 发布

您现在位置:Python中文网/ 问答频道 /正文

在试图解决LeetCode的几个问题时,我遇到了一个非常奇怪的问题。在

Question 26: Remove Duplicates from Sorted Array

https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/

Example:

Given nums = [1,1,2],

Your function should return length = 2, with the first two elements of 
nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the new length.

为了对这个问题进行编码,我使用了:

^{pr2}$

what this code is doing is first converting the list into a set and then back to list, which in turn will remove the Duplicates

但是当我试图将此代码提交给leetcode解决方案时,会返回nums的modified length,但是当程序试图访问nums数组时,它不会被更新。在

This is only Happening in Leetcode editor, in my system If I try to print the nums, the modified value is displayed, not sure what is wrong.

enter image description here

现在同样的情况也发生在其他问题上,例如:

Rotate Array https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/646/

Rotate an array of n elements to the right by k steps.

For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].

我对这个问题的解决办法如下:

class Solution(object):
 def rotate(self, nums, k):
    newIndex = k % len(nums)
    nums = nums[newIndex+1:len(nums)] + nums[0:newIndex+1]
    print nums

但我再次惊讶于我从提交文件中得到的结果。在

Note Here in the "Your STDOUT" we can see the list is modified accordingly. link to the Screenshot

请让我知道,如果有人面临这个问题,或有人知道这个问题的解决办法。在


Tags: andthetoinfromisarraywhat
3条回答

你可以用 sudo service network-manager restart

代码中发生的是返回的长度被用于在后端遍历nums,以打印nums列表的唯一值。所以,问题的关键是返回的长度将从索引0移动到返回的长度。因此,在返回唯一值的长度时,我们还必须修改原始列表,即nums。 第一条链路的解决方案

class Solution:
    def removeDuplicates(self, nums):
        if(len(nums) == 0):
            return 0
        elif len(nums) == 1 :
            return 1
        else:
            l = 1
            for i in range (1,len(nums)):
                if nums[i] != nums[i-1] :
                    #l+=1
                    nums[l] = nums[i]
                    l+=1
            return l

原来解决这个问题的方法是使用:nums[:] = nums[newIndex+1:len(nums)] + nums[0:newIndex+1]。在

执行nums = nums[newIndex+1:len(nums)] + nums[0:newIndex+1]只会更改引用,而nums[:]会更改列表的值。在

相关问题 更多 >