解答
public class Solution {
public int majorityElement(int[] nums) {
int length = nums.length;
int half = length / 2;
int value = -1;
Map<Integer, Integer> counters = new HashMap<>();
for (int num : nums) {
int count = counters.getOrDefault(num, 0);
counters.put(num, ++count);
if (count > half) {
value = num;
break;
}
}
return value;
}
}
要点
用例的设计思路:
- 数组的长度为偶数,比如数组长度为2,3有1个,1有1个,预期值为-1。
- 数组的长度为偶数,比如数组长度为4,3有3个,1有1个,预期值为3。
- 数组的长度为奇数,比如数组长度为7,2有4个,1有3个,预期值为4。
没有想到空间复杂度的为O(1)的方法。
准备的用例,如下
@Before
public void before() {
t = new Solution();
}
@Test
public void test001() {
assertEquals(2, t.majorityElement(new int[] { 2, 2, 1, 1, 1, 2, 2 }));
}
@Test
public void test002() {
assertEquals(5, t.majorityElement(new int[] { 1, 2, 5, 9, 5, 9, 5, 5, 5 }));
}
@Test
public void test003() {
assertEquals(-1, t.majorityElement(new int[] { 3, 2 }));
}