【无标题】

【java】输入一个无须有重复数组,输出一个新的数组,新的数组元素为指定重复次数的元素。

面试题:原题目带盖是这个意思

  1. 样例输入
  2. [1,3,3,2,4,1,3,2,2,1,2],3
  3. 样例输出
  4. [1, 3]

代码:

package com.chen.repeattimes;

import java.util.Arrays;

/**
 * 【样例输入1】[1.3,3,2.4.1,3.2.2.1.2],3
 * 【样例输出1】[1.3]
 * @author chenchen
 * @create 2022-10-22 20:13
 */
public class arraySameRepeat {
        public static void main(String[] args) {
            int[] nums = {1,3,3,2,4,1,3,2,2,1,2};
            int key = 3;
            int[] result = solution(nums, key);
            System.out.println(Arrays.toString(result));
//            for (int i = 0; i < result.length; i++) {
//                System.out.print(result[i]);
//            }
        }

    /**
     *
     * @param nums 输入的数组
     * @param key 指定的重复次数
     * @return
     */
    public static int[] solution(int[] nums, int key) {
            int n = nums.length;
            int[] result = new int[2];
            int x =0;
            for (int i = 0; i < n; i++) {
                int count =1;
                for (int j = i + 1; j < n; j++) {
                    if (nums[i] == nums[j]){
                        count ++;
                    }
                }
                if (count == key){
                    if (i==0){
                        result[x] = nums[i];
                        x++;
                    }else{
                        boolean flag = true;
                        for (int k = 0; k < i; k++) {
                            if (nums[i] == nums[k]) {
                                flag = false;
                            }
                        }
                        if (flag){
                            result[x] = nums[i];
                            x++;
                        }
                    }
                }

            }
            return result;
        }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值