[leetcode-python3] 26. Remove Duplicates from Sorted Array
1725 ワード
26. Remove Duplicates from Sorted Array - python3
Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means a modification to the input array will be known to the caller as well.
Internally you can think of this:// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);
// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}
My Answer 1: Wrong Answer
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
result = []
for i in nums:
if i not in result:
result.append(i)
return len(result)
どうしてだめなのか分からない
余分なメモリを使う...?
重複データ削除リストさえあればいいと思っていたのですが…理想
My Answer 2: Accepted (Runtime: 76 ms / Memory Usage: 16.1 MB)
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
i=0
for j in range(1,len(nums)):
if nums[j]!=nums[j-1]:
i+=1
nums[i]=nums[j]
return i+1
numsのみを使用して比較し、メモリを追加する必要はありません.
非繰返しを前方に引き出し、長さを表すi+1を返す
Reference
この問題について([leetcode-python3] 26. Remove Duplicates from Sorted Array), 我々は、より多くの情報をここで見つけました
https://velog.io/@jsh5408/leetcode-python3-26.-Remove-Duplicates-from-Sorted-Array
テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol
// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);
// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
result = []
for i in nums:
if i not in result:
result.append(i)
return len(result)
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
i=0
for j in range(1,len(nums)):
if nums[j]!=nums[j-1]:
i+=1
nums[i]=nums[j]
return i+1
Reference
この問題について([leetcode-python3] 26. Remove Duplicates from Sorted Array), 我々は、より多くの情報をここで見つけました https://velog.io/@jsh5408/leetcode-python3-26.-Remove-Duplicates-from-Sorted-Arrayテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol