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

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;

/**
*   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
{
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);
}
}


//------------------------------------------------------------------------------------------------------
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

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


• 本文已收录于以下专栏：

举报原因： 您举报文章：Java面试作业，给一个整型数组，要求算出最多相同value的sum，类似二叉树搜索； 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)