跳过正文
  1. Posts/

leetcode 80 Remove Duplicates from Sorted Array II (有序数组去除重复元素)

·1 分钟

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.

Subscribe to see which companies asked this question.

题意:一个有序数组,每个元素最多出现两次,如果大于两次,把多的去掉,返回去掉后的数组长度len,以及要求数组前len是去掉那些元素之后的元素。//语死早。。看原题好了。。

思路:排序了还不是随便搞? 没要求空间再开一个标记空间。。。O(1)空间的话。。就乱搞一下?

 1/* ***********************************************
 2Author :111qqz
 3Created Time :2017年04月05日 星期三 21时25分48秒
 4File Name :80.cpp
 5************************************************ */
 6class Solution {
 7
 8public:
 9
10    int removeDuplicates(vector<int>& nums) {
11    int siz = nums.size();
12    if (siz==0) return 0;
13    int p = 0;
14    int magic = -324784312;
15    for ( int i = 0 ; i < siz-1 ; i++)
16    {
17        if (nums[i]==nums[i+1]) p++;
18        else p = 0;
19        if (p>=2) nums[i-1] = magic;
20    }
21    int cur = 0;
22    for ( int i = 0 ; i < siz ; i++)
23    {
24        if (nums[i]!=magic) nums[cur++] = nums[i];
25    }
26    return cur;
27
28    }
29
30};

相关文章

leetcode 289. Game of Life (模拟)

·3 分钟
According to the Wikipedia’s article: “The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.” Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):