Java面试作业,给一个整型数组,要求算出最多相同value的sum,类似二叉树搜索;

原创 2015年11月18日 07:03:29

题目:

Given an array of integers, find the sum of the most common integer

直接上代码:

package com.intelematics.findmostcommon;

import java.util.HashMap;
import java.util.Arrays;

/**
 * Intelematics Task:
 *   Given an array of integers, find the sum of the most common integer
 * Assumptions:
 * 	 1: The test array size is in a reasonable range (Depend on the memory size)
 *   2: The count of the same number in the given array is different to each other(Array like {0,0,1,1} is invalid)
 * @author: Tony
 * @since: 12/11/2015
 */

public class SumCommonInteger {
	
	/**
	 * Find the sum of the most common integer
	 * Optimized for runtime
	 * Runtime: O(n)
	 * Space: O(n)
	 * @param int[] inputIntArray
	 * @return sum result
	 */
	public static int sumCommonForRuntime(int[] inputIntArray)
	{
		// Temporary store may occupy memory space whereas more rapid for runtime.
		HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
		// Store the final result occupy memory space
		int common[] = new int[] {0, 0};
		try
		{
			// Iterate over the array while keep it still		
			for(int key : inputIntArray) 
			{
				// hm is rapid for seeking by key
				if(hm.containsKey(key))
				{
					Integer commonCount = hm.get(key);
					commonCount ++;
					// count ++; if true update to another key count
					if(commonCount > common[1])
					{
						common[0] = key;
						common[1] = commonCount;
						// Dynamically update the hm, occupy more memory space
						hm.put(key, commonCount);
					}
				} 
				else 
				{
					// First put count=1
					hm.put(key, 1);
				}
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		
		return common[0]*common[1];
	}
	
	/**
	 * Find the sum of the most common integer
	 * Optimized for memory space
	 * Runtime: O(nlogn)--O(n^2)
	 * Space: O(n)
	 * @param int[] inputIntArray
	 * @return sum result
	 */
	public static int sumCommonForSpace(int[] inputIntArray)
	{
		// Store the final result occupy memory space
		int common[] = new int[] {0, 0};
		Arrays.sort(inputIntArray);
		
		try
		{
			// Iterate over the array while keep it still
			for(int i=1; i<inputIntArray.length; i++) 
			{
				int currCount = 0;
				int currKey = 0;
				for(int j=0; j<inputIntArray.length-1; j++) 
				{
					if(inputIntArray[j] == inputIntArray[i])
					{
						currKey = inputIntArray[i];
						currCount ++;
						// After currCount ++; if true update to another key count
						if(currCount > common[1])
						{
							common[0] = currKey;
							common[1] = currCount;
						}
					}
				}
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		
		return common[0]*common[1];
	}

	/**
	 * Main
	 * @param args
	 */
	public static void main(String[] args) 
	{
		int[] inputIntArray = new int[]{1,2,3,4,5,1,8};
		System.out.println("Result of sumCommonForRuntime: "+sumCommonForRuntime(inputIntArray));
		System.out.println("Result of sumCommonForSpace: "+sumCommonForSpace(inputIntArray));
	}
	
}

Junit测试代码:

package com.intelematics.findmostcommon;

import static org.junit.Assert.*;

import org.junit.Test;

/**
 * Test Case for SumCommonInteger
 * @author Tony
 * @since 12/11/2015
 */
public class SumCommonIntegerTest {

	@Test
	public void testSumCommonForRuntimeNormal() 
	{
		int[] inputIntArray = new int[]{1,2,3,4,5,1,8};
		assertEquals(SumCommonInteger.sumCommonForRuntime(inputIntArray), 2);
	}

	@Test
	public void testSumCommonForRuntimeNull() 
	{
		int[] inputIntArray = new int[]{};
		assertEquals(SumCommonInteger.sumCommonForRuntime(inputIntArray), 0);
	}

	@Test
	public void testSumCommonForRuntimeInvalid() 
	{
		int[] inputIntArray = new int[]{3,3,0,0,1,1,2,2};
		assertEquals(SumCommonInteger.sumCommonForRuntime(inputIntArray), 6);
	}

	@Test
	public void testSumCommonForRuntimeNeg() 
	{
		int[] inputIntArray = new int[]{-1,2,-3,4,5,-1,-8};
		assertEquals(SumCommonInteger.sumCommonForRuntime(inputIntArray), -2);
	}
	
	@Test
	public void testSumCommonForRuntimeSame() 
	{
		int[] inputIntArray = new int[]{1,1,1,1,1,1,1};
		assertEquals(SumCommonInteger.sumCommonForRuntime(inputIntArray), 7);
	}
	//------------------------------------------------------------------------
	@Test
	public void testSumCommonForSpaceNormal() 
	{
		int[] inputIntArray = new int[]{1,2,3,4,5,1,8};
		assertEquals(SumCommonInteger.sumCommonForSpace(inputIntArray), 2);
	}

	@Test
	public void testSumCommonForSpaceNull() 
	{
		int[] inputIntArray = new int[]{};
		assertEquals(SumCommonInteger.sumCommonForSpace(inputIntArray), 0);
	}

	@Test
	public void testSumCommonForSpaceInvalid() 
	{
		int[] inputIntArray = new int[]{3,3,0,0,1,1,2,2};
		assertEquals(SumCommonInteger.sumCommonForSpace(inputIntArray), 6);
	}

	@Test
	public void testSumCommonForSpaceNeg() 
	{
		int[] inputIntArray = new int[]{-1,2,-3,4,5,-1,-8};
		assertEquals(SumCommonInteger.sumCommonForSpace(inputIntArray), -2);
	}
	
	@Test
	public void testSumCommonForSpaceSame() 
	{
		int[] inputIntArray = new int[]{1,1,1,1,1,1,1};
		assertEquals(SumCommonInteger.sumCommonForSpace(inputIntArray), 7);
	}
}


ReadMe:

//------------------------------------------------------------------------------------------------------
Problem:
Given an array of integers, find the sum of the most common integer.
Example: (1, 2, 3, 4, 5,1, 8) returns 2 (as 1+1 = 2) .

//------------------------------------------------------------------------------------------------------
My Solution Details:
* Assumptions:
*  1: The test array size is in a reasonable range (Depend on the memory size)
*  2: The count of the same number in the given array is different to each other(Array like {0,0,1,1}, is no sense)

First: Optimized for runtime [Implemented in java]
1. Use HashMap<Integer, Integer> to store the count of each value in the given array, this will occupy memory space.
2. Use int common[] to store the final result, this will occupy memory space.
3. Iterate over the given array while keep it still, use HashMap for a rapid seeking by key.
4. Use hm.put(key, commonCount), dynamically update the hm, in terms of the given array, occupy more memory space.
5. return common[0]*common[1];

If the first value in the given array is the most common one, the minimum runtime would be O(n) and so would be the memory space.

Second: Optimized for space [Described as the following]
1. Use int common[] to store the final result, this will occupy memory space.
2. UseArrays.sort() to sort the given array, depends on the array, this may cost lots of time.
3. Iterate over the given array from 1 to array.length, compare each value to its left one(from 0 to length-1), this may cost lots of time too.
4. Get the most common one and update common[]
5. return common[0]*common[1];

In this solution, I just use the given array and the result array, it take only few bytes of extra memory space for the variables themselves. At the same time, the longest time for running would be O(n^2) and average time would be O(nlogn).

//------------------------------------------------------------------------------------------------------
In my past projects, in most cases, we took the first into effect rather than the second one, as the requirements for runtime speed outweigh for memory cost.

//------------------------------------------------------------------------------------------------------
Please feel free to copy the following lines to execute it in command line in current file dir. [java version "1.8.0_60"]
javac -d . SumCommonInteger.java
java com.intelematics.findmostcommon.SumCommonInteger

//------------------------------------------------------------------------------------------------------



二叉查找树BST----java实现

二叉查找树BST----java实现 1.二叉查找树简介 二叉查找树又名二叉搜索树和二叉排序树。性质如下:   在二叉查找树中: (01) 若任意节点的左子树不空,则左子树上所有结点的值均小于它的根结...
  • u010093630
  • u010093630
  • 2014年08月07日 01:02
  • 5957

算法导论第十二(12)章 二叉查找树

12.1 二叉查找树
  • z84616995z
  • z84616995z
  • 2014年06月06日 15:11
  • 4520

算法导论12.2查询二叉搜索树 练习总结

12.2-1 假设一棵二叉搜索树中的结点在 1 到 1000 之间,现在想要查找数值为 363 的结点。下面序列中哪个不是查找过的序列? a. 2, 252, 401, 398,330,344,397...
  • chan15
  • chan15
  • 2015年09月28日 18:56
  • 1351

一个整型数组里除了一个或者两个或者三个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)

题目中包括三个小的问题,由简单到复杂: 1,如果只有一个出现一次,考察到异或的性质,就是如果同一个数字和自己异或的活结果为零,那么循环遍历一遍数组,将数组中的元素全部做异或运算,那么出现两次的数字全...
  • immiao
  • immiao
  • 2013年12月29日 12:51
  • 720

一个整型数组里除了两个数字之外,其他的数字都出现了两次。 请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n), 空间复杂度是O(1)

题目:一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)。 思路:题目要求时间复杂度是O(n),空间复杂度是O(...
  • leolinsheng
  • leolinsheng
  • 2013年07月23日 17:30
  • 1473

一个整型数组里除了一个或者两个或者三个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)

粗糙的给出了分析,最近比较累,以后会改进的。 题目中包括三个小的问题,由简单到复杂: 1,如果只有一个出现一次,考察到异或的性质,就是如果同一个数字和自己异或的活结果为零,那么循环遍历一遍...
  • zzran
  • zzran
  • 2012年10月24日 21:09
  • 13343

23rd Feb: 数组(搜索专题)和二叉树(Path Sum专题)

162. Find Peak Element A peak element is an element that is greater than its neighbors. Given an...
  • Firehotest
  • Firehotest
  • 2017年02月25日 00:03
  • 200

【LeetCode-面试算法经典-Java实现】【108-Convert Sorted Array to Binary Search Tree(排序数组转变为平衡二叉树)】

【108-Convert Sorted Array to Binary Search Tree(排序数组转变为平衡二叉树)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题  ...
  • DERRANTCM
  • DERRANTCM
  • 2015年08月10日 07:38
  • 2296

找出一个数组中重复次数最多的字符暨找出Map中的最大Value及其对应的Key

rt:找出Map中的最大Value及其对应的Key,常用于找出一个数组中重复次数最多的字符import java.util.*; public class KeyOnMaxValue{ public...
  • qq_30629571
  • qq_30629571
  • 2016年06月15日 21:19
  • 438

程序员面试金典——解题总结: 9.18高难度题 18.3编写一个方法,从大小为n的数组中随机选出m个整数。要求每个元素被选中的概率相同。

#include #include #include using namespace std; /* 问题:编写一个方法,从大小为n的数组中随机选出m个整数。要求每个元素被选中的概率相同。 分...
  • qingyuanluofeng
  • qingyuanluofeng
  • 2017年01月18日 14:44
  • 606
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Java面试作业,给一个整型数组,要求算出最多相同value的sum,类似二叉树搜索;
举报原因:
原因补充:

(最多只允许输入30个字)