Leetcode刷题记—— Remove Duplicates from Sorted Array II(已排序数组移除重复元素2)

来源:互联网 发布:网络文学作品 编辑:程序博客网 时间:2024/05/09 19:11

一、题目叙述:

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 1122 and 3. It doesn't matter what you leave beyond the new length.

Subscribe to see which companies asked this question.

排序数组中一个元素最多只能重复2次,将多余的移除

二、解题思路:

Medium题。

思路:

(1)倒着遍历数组,若当前元素与其前前一个元素的值不同,计数加1;否则,将后续元素前移。

(2)注意当数组元素小于等于2的情况。

三、源码:

import java.util.Arrays;public class Solution  {  public int removeDuplicates(int[] nums){  if (nums.length <= 2) return nums.length;      int count = 2;      for (int i = nums.length - 1; i >= 2; i--)      {      if (nums[i] != nums[i - 2])      count ++;      else       for (int j = i; j < nums.length - 1; j ++)      nums[j] = nums[j + 1];      }      System.out.println(Arrays.toString(nums));      return count;          }    public static void main(String args[])          {                                  Solution solution = new Solution();              int[] nums = {1, 1, 1, 2, 2, 3};      System.out.println(solution.removeDuplicates(nums));     }      }  


0 0
原创粉丝点击