前言:
这是另一道AC出来的笔试题,在这里分享一下。
题目描述
已知有序正整数数组,删除数组中重复的数组,使得数组中数字满足下面要求:数字1最多允许出现一次,数字2最多允许出现两次,以次内推,数字为n(n>0)最多允许出现n次。返回满足条件的数组中数组长度的最大值。
输入描述
1 1 1 2 2 2 3 3 3
输出:
6
题目解析
我这道题的思路就是统计每个数字出现的次数,根据次数来做加减,如果次数大于等于自己则最大为自己本身,如果小于,则按次数进行加减。
代码如下:
package Shopee;
import java.util.Scanner;
public class Main1 {
public static int removeArray(int[] array)
{
if(array.length==0)
{
return 0;
}
int i = 0;
int count = 0;
int result = 0;
for (int j = 0; j <= array.length-1; j++) {
//一个数字统计个数
if(array[j] != array[i])
{
if(count>=array[i])
{
result +=array[i];
}else {
result =count;
}
i = j;
count = 0;
}
count++;
}
if (count >= array[i]) {
result += array[i];
} else {
result = count;
}
return result;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext())
{
String s = scanner.nextLine();
String[] array = s.split(" ");
int[] arrays = new int[array.length];
for (int i = 0; i < array.length; i++) {
arrays[i] = Integer.parseInt(array[i]);
}
int length = removeArray(arrays);
System.out.println(length);
}
}
}