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

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



相关文章推荐

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

162. Find Peak Element A peak element is an element that is greater than its neighbors. Given an...

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

【108-Convert Sorted Array to Binary Search Tree(排序数组转变为平衡二叉树)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题  ...

一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字

题目:一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n) ,空间复杂度是O(1) 。分析:这是一道很新颖的关于位运算的面试题。首先我们...
  • erazy0
  • erazy0
  • 2011年05月24日 17:56
  • 1805

找出一个整型数组中只出现了一次的数字

要求:一个整型数组中除了两个数字外(记为X,Y),其余数字都出现了两次,请写程序找出这两个只出现了一次的数字,要求:时间复杂度为O(n),空间复杂度为O(1)。      思路:假设数组中只有一个数字...
  • htq__
  • htq__
  • 2016年03月12日 21:27
  • 738

[算法学习]给定一个整型数组,找出两个整数为指定整数的和(1)

问题描述:给定一个整型数组,是否能找出其中的两个数使其和为某个指定的值?(假定是无序数组) 解法一:暴力破解(穷举法,不提倡) /** * 暴力破解 * (穷举,时间复杂度:...

求一个整型数组的最大和的子数列,要求时间复杂度为线性的

/** * 有一个整形数组,求其连续和最大值的字串,时间复杂度是O(n) * 如果元素全部为正数或者负数则没有意义。 * 一般实现此算法有三种复杂度 * O(n^3),O(nlgn),O(n)...

课堂在线Java程序设计作业求两个数组相同元素个数

给定两个数组(数组中不包含相同元素),求两个数组的交集中元素的个数(即共同出现的数,如没有则输出为None) 如输入: 5 1 2 4 6 8 6 1 2 5 6 7 8 输出: 4 im...

[算法学习]给定一个整型数组,找出两个整数为指定整数的和(2)

问题描述:给定一个整型的数组,找出其中的两个数使其和未指定的值,返回两个数的数组下标(假定是无序数组,数组元素各不相同,要求时间复杂度为O(n),n为数组长度,可以使用辅助空间) 分析:时间...

一个整型数组里除了两个数之外,其他数都出现了两次。找出这两个出现一次的数。

第一个想法是借助辅助数组以及折半插入来实现 第二个想法是通过 异或运算 实现...

java 判断两个二叉树是否完全相同

java 判断两个二叉树是否完全相同 包括了创建二叉树,前序遍历输出(递归),比较二叉树是否相同。 package com.yuxin.learn; import java.util.Linke...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Java面试作业,给一个整型数组,要求算出最多相同value的sum,类似二叉树搜索;
举报原因:
原因补充:

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