[LeetCode]题解(python):80-Remove Duplicates from Sorted Array II
题目来源
https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array nums = [1,1,1,2,2,3]
,
Your function should return length = 5
, with the first five elements of nums being 1
, 1
, 2
, 2
and 3
. It doesn't matter what you leave beyond the new length.
题意分析
Input: type numsList[int];
Output: rtype int;
Conditions:删除array中的重复元素,但是允许重复次数为2,保证返回的length长度下包含所需值,大于length长度的元素不考虑
题目思路
穷举思路,只要出现过两次,就将该元素忽略。其实因为数组是有序的,穷举效率肯定差一点,但是leetcode OJ通过了= =
AC代码(Python)
class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ k = 0 l = len(nums) if l == 0: return 0 for i in range(l): t = 0; for j in range(k): if nums[i] == nums[j]: t+=1 if t < 2: nums[k] = nums[i] k += 1 #for i in range(k): # print(str(nums[i]) + " ") return k
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步