Integer[] array = new Integer[]{1,2,3,1,2,3,4};如何取到4?
1 回答

阿晨1998
TA貢獻(xiàn)2037條經(jīng)驗(yàn) 獲得超6個(gè)贊
import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.HashMap;import java.util.Random;public class FindRepetition { private static final int index = 100000; private static int[] nums = new int[index]; static { Random random = new Random(); for(int i = 0; i < index; i++) { nums[i] = random.nextInt(index); } } public static void main(String... args) { long startTime1 = System.currentTimeMillis(); List<Integer> result1 = findRepetitionTime(nums); System.out.println(String.format("時(shí)間效率優(yōu)先,耗時(shí):%s", (System.currentTimeMillis() - startTime1))); long startTime2 = System.currentTimeMillis(); List<Integer> result2 = findRepetitionSpace(nums); System.out.println(String.format("時(shí)間效率優(yōu)先,耗時(shí):%s", (System.currentTimeMillis() - startTime2))); } //時(shí)間效率優(yōu)先 private static List<Integer> findRepetitionTime(int... nums) { List<Integer> result = new ArrayList<Integer>(); Map<Integer, Integer> countMap = new HashMap<Integer, Integer>(8); for(int num: nums) { if(countMap.containsKey(num)) { countMap.put(num, countMap.get(num)); } else { countMap.put(num, 1); } } for(Map.Entry<Integer,Integer> entry: countMap.entrySet()) { if(entry.getValue() == 1) { result.add(entry.getKey()); } } return result; } //空間效率優(yōu)先 private static List<Integer> findRepetitionSpace(int... nums) { List<Integer> result = new ArrayList<Integer>(); for (int i = 0; i < nums.length; i++) { int count = 0;//標(biāo)記重復(fù)次數(shù) for (int j = 0; j < nums.length; j++) { if(nums[i] != nums[j]) { count++; } if(count==nums.length-1) { result.add(nums[i]); break; } } } return result; } }
print:
時(shí)間效率優(yōu)先,耗時(shí):78空間效率優(yōu)先,耗時(shí):8102
上面的代碼是兩種方法的時(shí)間對(duì)比,時(shí)間和空間自己衡量,至于那種方法更好,各有各的優(yōu)點(diǎn)。第一個(gè)消耗的空間多一點(diǎn),第二個(gè)耗時(shí)長一點(diǎn)
添加回答
舉報(bào)
0/150
提交
取消