数据结构面试题1.2.2-下排每个数都是先前上排那十个数在下排出现的次数

package questions;

/**
 * @title 下排每个数都是先前上排那十个数在下排出现的次数
 * @question 给你10分钟时间,根据上排给出的十个数,在其下排填出对应的十个数,要求下排每个数都是先前上排那十个数在下排出现的次数。
 *           上排的十个数如下:<br>
 *           [0,1,2,3,4,5,6,7,8,9] <br>
 *           举一个例子,<br>
 *           数值:0,1,2,3,4,5,6,7,8,9 <br>
 *           分配:6,2,1,0,0,0,1,0,0,0<br>
 *           0在下排出现了6次,1在下排出现了2次,2在下排出现了1次,3在下排出现了0次...<br>
 *           以此类推...<br>
 *           10 0 0 0 0 0 0 0 0 0<br>
 *           9 0 0 0 0 0 0 0 0 1<br>
 *           8 1 0 0 0 0 0 0 1 0<br>
 *           7 2 0 0 0 0 0 1 0 0<br>
 *           6 2 1 0 0 0 1 0 0 0<br>
 *           6 2 1 0 0 0 1 0 0 0<br>
 *           0 1 2 3 4 5 6 7 8 9<br>
 *           6 2 1 0 0 0 1 0 0 0<br>
 * @author Sam
 *
 */
public class Ex1o2o2 {
	public static void main(String[] args) {
		int[] a = BottomArrGenerate.generateArr(10);
		printArr(a);
	}

	private static void printArr(int[] a) {
		if (null != a) {
			for (int i = 0; i < a.length; i++) {
				System.out.print(String.format("%d ", i));
			}
			System.out.println();
			for (int i = 0; i < a.length; i++) {
				System.out.print(String.format("%d ", a[i]));
			}
		}
	}
}

class BottomArrGenerate {

	/**
	 * 结果和题目相符
	 * 
	 * @param n
	 * @return
	 */
	public static int[] generateArr(int n) {
		if (n < 4) {
			System.out.println("请输入不小于4的整数");
			return null;
		}
		int[] bottom = new int[n];// 默认值都为0

		// 遍历本身数组并赋值,如果当前数组key值和计算出现key次数不等,则需要重新赋值
		// 一般为第5次出正确结果
		for (int m = 0; m < n + 2; m++) {
			boolean flag = true;// 找到结果标志
			System.out.print(String.format("第%s次遍历:", m + 1));
			for (int i = 0; i < n; i++) {// 逐位对应
				int count = getCount(i, bottom);
				System.out.print(String.format("%d ", count));
				if (bottom[i] != count) {// 和上一次计算结果不符
					bottom[i] = count;
					flag = false;
				}
			}
			System.out.println();
			if (flag) {// 连续两次得到的次数一样,则为正确结果
				break;
			}

			if (m == n + 1 && !flag) {
				// 算法有缺陷,n=5时是有结果2,1,2,0,0(2,0,2,0,0)的,底下结果如果有2个数字等于上面的数字就算不出来
				System.out.println("找不到结果");
				return null;
			}
		}
		return bottom;
	}

	public static int[] generateArray(int n) {
		if (n < 4) {
			System.out.println("请输入不小于4的整数");
			return null;
		}
		int[] bottom = new int[n];// 默认值都为0
		return bottom;
	}

	/**
	 * 获得某数在数组中出现的次数
	 * 
	 * @param num
	 *            数
	 * @param arr
	 *            数组
	 * @return 数字在数组中出现的次数
	 */
	private static int getCount(int num, int[] arr) {
		int count = 0;
		for (int i = 0; i < arr.length; i++) {
			if (num == arr[i]) {
				count++;
			}
		}
		return count;
	}
}
直接分析: http://blog.csdn.net/wcyoot/article/details/6428305
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值