[英]Leetcode Python Issue
在嘗試解決LeetCode的一些問題時,我面臨着一個非常奇怪的問題。
問題26:從排序數組中刪除重復項
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.
為了編碼這個問題,我使用了:
class Solution(object):
def removeDuplicates(self, nums):
nums = list(set(nums))
return len(nums)
這段代碼要做的是先將列表轉換為集合,然后再返回列表,這將刪除重復項
但是,當我嘗試將此代碼提交給leetcode解決方案時,將返回已修改的nums長度,但是當程序嘗試訪問nums數組時,它不會更新。
這僅在我的系統中的Leetcode編輯器中發生。如果我嘗試打印num,則會顯示修改后的值,不確定是什么錯誤。
現在,同樣的情況也發生在其他問題上,例如:
旋轉陣列https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/646/
將k個元素向右旋轉n個元素的數組。
例如,在n = 7和k = 3的情況下,數組[1,2,3,4,5,6,7]旋轉為[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
但是我再次對提交的輸出感到驚訝。
注意在這里,在“您的標准輸出”中,我們可以看到列表已被相應修改。 鏈接到截圖
如果有人遇到此問題或知道解決方案,請告訴我。
您可以使用sudo service network-manager restart
原來的解決方案是使用: nums[:] = nums[newIndex+1:len(nums)] + nums[0:newIndex+1]
。
執行nums = nums[newIndex+1:len(nums)] + nums[0:newIndex+1]
只會更改引用,而nums[:]
更改列表的值。
您的代碼中發生的是返回的長度用於在后端移動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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.