class Solution(object): def removeDuplicates(self, nums): pre, idx = None, 0 for i in range(len(nums)): if nums[i] != pre: nums[idx], pre, idx = nums[i], nums[i], idx + 1 return idx
Hi @StefanPochmann ， I designed my algorithm with a virtual writer and that's what 'idx' does, the sufficient and necessary condition is that reader 'i' is different than what writer 'idx' previously wrote. Any suggestion or advice is very welcomed!
Ah, sorry I was unclear. I'm not talking about
idx, just about
i. I was wondering why you didn't just do this:
def removeDuplicates(self, nums): pre, idx = None, 0 for num in nums: if num != pre: nums[idx], pre, idx = num, num, idx + 1 return idx
But I guess yours might be (or at least appear to be) safer. If it were a really critical piece of software, I might look for guarantees and maybe do it your way as well, but here I can't be bothered and just assume that Python implements the looping as one would assume. Apparently I've made that such a habit that the possible problem really didn't occur to me when I asked up there :-)
@StefanPochmann Yes, I think that will be a good point to use
for ele in arr: instead of
for i in range(len(arr)): but for me it took a second round to format the style of the code. I do pursue a concise piece of code to get rid of all the extra logic parts and syntax, since less code is usually more intuitive and probably less bugs. And my paragon is "E = M^2" :-p
But do you know whether it's guaranteed to be safe? I think last time I checked, I couldn't really find anything...
Ok, found something now. The documentation does talk about a counter, as one would assume:
An internal counter is used to keep track of which item is used next, and this is incremented on each iteration. When this counter has reached the length of the sequence the loop terminates.
So I'd say it should indeed be fine.
Great ref! And a flawless template seems to appear:
for x in a[:]: if x < 0: a.remove(x)
Designed for cases of
delete operations though.
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.