【算法】数组面试题 用面向对象的方法求出数组中重复 value的个数,按如下个数输出:

用面向对象的方法求出数组中重复 value 的个数,按如下个数输出:

1 出现:1 次 
3 出现:2 次 
8 出现:3 次 
2 出现:4 次 
 
int[] arr = {1,4,1,4,2,5,4,5,8,7,8,77,88,5,4,9,6,2,4,1,5}; 
 

首先我们想到创建一个较大的数组,用两次循环遍历来实现,第一次循环记录每个数字出现的次数,第二次遍历输出题目要求的格式。

		int[] arr = {1,4,1,4,2,5,4,5,8,7,8,77,88,5,4,9,6,2,4,1,5};
		System.out.println("arr.length:" + arr.length);
		
		int[] arrNum = new int[126];	// 创建一个新数组
		
		for (int i = 0; i < arr.length; i++) {
			arrNum[arr[i]]++;	// 用来记录某元素出现的次数
		}
		
		for (int i = 0; i < arrNum.length; i++) {
			if (arrNum[i] != 0) {
				System.out.println(i + "出现:" + arrNum[i] + "次");
			}
		}

但是这样出现一个问题,就是新数组的长度问题,若原数组中的最大值非常大,那么就会产生资源浪费问题,并且遍历次数过多。

 

然后我们想到用Map来实现,Map是key-value键值对形式的,与题意相符合。

并且HashMap中不允许重复的key。实现代码如下;

package com.xzq;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: java8_demo
 * @description: 用面向对象的方法求出数组中重复 value的个数
 * @author: XZQ
 * @create: 2020-01-09 20:32
 **/
public class ArrayDemo {
    public static void main(String[] args) {
        int[] arr = {1, 4, 1, 4, 2, 5, 4, 5, 8, 7, 8, 77, 88, 5, 4, 9, 6, 2, 4, 1, 5};

        ArrayDemo arrayDemo = new ArrayDemo();
        arrayDemo.countAndSout(arr);
    }

    public void countAndSout(int arr[]) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < arr.length; i++) {
            int a = arr[i];
            if (!map.containsKey(a)) {
                map.put(a, 1);
            } else {
                Integer integer = map.get(a);
                integer++;
                map.put(a, integer);
            }
        }

        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            Integer key = entry.getKey();
            Integer value = entry.getValue();
            System.out.println(key + " 出现:" + value + "次");
        }
    }
}

 

输出结果:

1 出现:3次
2 出现:2次
4 出现:5次
5 出现:4次
6 出现:1次
7 出现:1次
8 出现:2次
88 出现:1次
9 出现:1次
77 出现:1次

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值