在试图解决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.
现在同样的情况也发生在其他问题上,例如:
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
请让我知道,如果有人面临这个问题,或有人知道这个问题的解决办法。在
你可以用
sudo service network-manager restart
代码中发生的是返回的长度被用于在后端遍历
nums
,以打印nums
列表的唯一值。所以,问题的关键是返回的长度将从索引0移动到返回的长度。因此,在返回唯一值的长度时,我们还必须修改原始列表,即nums
。 第一条链路的解决方案原来解决这个问题的方法是使用:
nums[:] = nums[newIndex+1:len(nums)] + nums[0:newIndex+1]
。在执行
nums = nums[newIndex+1:len(nums)] + nums[0:newIndex+1]
只会更改引用,而nums[:]
会更改列表的值。在相关问题 更多 >
编程相关推荐