题解 | #数组中出现次数超过一半的数字#
数组中出现次数超过一半的数字
http://www.nowcoder.com/questionTerminal/e8a1b01a2df14cb2b228b30ee6a92163
审题: 数字大于0,出现次数超过一半,且一定有解,那么每次移除两个不一样的数字即可,剩下的就是答案 为了节省空间,所有处理过的数据标记为-1
fun MoreThanHalfNum_Solution3(numbers: IntArray): Int {
// println("input array count: ${numbers.size},list: ${numbers.contentToString()}")
val size = numbers.size
if(size== 1) return numbers[0];
for (a in 0..size-2) {
//println("input array a: ${a},list: ${numbers.contentToString()}")
if(numbers[a] < 0) continue
for (b in a+1..size-1) {
if(numbers[b] < 0 || numbers[a] == numbers[b]) continue
if(b == size-1) { // 到底了,说明a对应的就是答案
return numbers[a]
}
numbers[a] = -1
numbers[b] = -1
break
}
}
//println("input array a: ${a},list: ${numbers.contentToString()}")
return numbers[size-1] // 还剩下一个时
}