【剑指offer-28】20190814/01 数组中出现次数超过一半的数字

【剑指offer-28】数组中出现次数超过一半的数字

  • 考点:数组
  • 时间限制:1秒
  • 空间限制:32768K
  • 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0

思路:

思路一:数组排序后,如果符合条件的数存在,则一定是数组中间那个数。(比如:1,2,2,2,3;或2,2,2,3,4;或2,3,4,4,4等等)
【这种方法1是需要自己写sort代码,2就是调用Arrays.sort辅助排序】
这个思路就是:

  1. 对数组先进行排序。
  2. 统计中间那个数字出现的次数,用count保存。
  3. 如果出现次数count超过数组长度的一半,那么返回这个数字,否则就返回0。
代码:
// 使用Arrays.sort()辅助进行排序
import java.util.Arrays;
public class Solution {
    public int MoreThanHalfNum_Solution(int [] array) {
        Arrays.sort(array);
        int count = 0;
        int num = array[array.length / 2];
        int len = array.length;
        for (int i = 0; i < len; i++) {
            if (array[i] == num) {
                count++;
            }
        }
        if (count > (len / 2)) {
            return num;
        } else {
            return 0;
        }
    }
}
public class Solution {
    public int MoreThanHalfNum_Solution(int [] array) {
        // 自己写了快速排序
        QuickSort(array, 0, array.length - 1);
        int count = 0;
        int num = array[array.length / 2];
        int len = array.length;
        for (int i = 0; i < len; i++) {
            if (array[i] == num) {
                count++;
            }
        }
        if (count > (len / 2)) {
            return num;
        } else {
            return 0;
        }
    }
    public void QuickSort(int[] array, int low, int high) {
        if (low < high) {
            // 找寻基准数据的正确索引
            int index = getIndex(array, low, high);
            
            // 进行迭代
            QuickSort(array, low, index - 1);
            QuickSort(array, index + 1, high);
        }
    }
    
    public int getIndex(int[] array, int low, int high) {
        // 基准数据
        int pivot = array[low];
        while (low < high) {
            // 当队尾的元素大于等于基准数据时,向前挪动high指针
            while (low < high && array[high] >= pivot) {
                high--;
            }
            // 如果队尾元素小于pivot了,需要将其赋值给low
            array[low] = array[high];
            // 当队首元素小于等于pivot时,向前挪动low指针
            while (low < high && array[low] <= pivot) {
                low++;
            }
             // 当队首元素大于tmp时,需要将其赋值给high
            array[high] = array[low];
        }
        // 跳出循环时low和high相等,此时的low或high就是tmp的正确索引位置
        // low位置的值并不是pivot,所以需要将pivot赋值给arr[low]
        array[low] = pivot;
        return low; // 返回tmp的正确位置
    }
    
}
我的问题:
  1. 在思路1中,count一定要大于数组长度的一半。我一开始把条件写成了大于等于,结果有部分样例测试没有通过。
  2. 复习了快速排序,快速排序还是不太熟。

其他思路1:

思路二:如果有符合条件的数字,则它出现的次数比其他所有数字出现的次数和还要多。
在遍历数组时保存两个值:一是数组中一个数字,一是次数。.
遍历下一个数字时,若它与之前保存的数字相同,则次数加1,否则次数减1;若次数为0,则保存下一个数字,并将次数置为1。遍历结束后,所保存的数字即为所求。然后再判断它是否符合条件即可。

public class Solution {
    public int MoreThanHalfNum_Solution(int [] array) {
        int count = 1; // 次数
        int num = array[0]; // 保存数字
        
        int len = array.length;
        for (int i = 1; i < len; i++) {
            if (array[i] == num) {
                count++;
            } else {
                count--;
            }
            if (count == 0) {
                // 更新数字为当前所遍历到的数字,并且设置count为1
                num = array[i];
                count = 1;
            } 
        }

        count = 0;
        // 判断这个数字是否出现的长度超过了数组的一半
        for (int i = 0; i < len; i++) {
            if (num == array[i]) {
                count++;
            }
        }
        if (count > len / 2) {
            return num;
        } else {
            return 0;
        }
    }
}

在这里有个地方要注意,就是一开始count置数为1,然后数组遍历的时候是从第1个元素开始查找。

  • 如果此时第一个元素==第0个元素(num),那么count++,否则count–
  • 此时如果执行count–,那么count==0了。这个时候将num置为第1个元素,继续从下一个元素继续遍历。
    判断的地方还是一样的,判断这个数字出现的次数,如果大于数组长度的一半那么返回这个数字,否则返回0。

其他思路2:

借助HashMap。

  • 首先是统计在数组中,每个数字出现的个数。
  • 然后进行遍历这个HashMap。
  • 如果这个值出现的次数大于了长度一半,返回这个值,在遍历结束之后,返回0。
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class Solution {
    public int MoreThanHalfNum_Solution(int [] array) {
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        int len = array.length;
        for (int i = 0; i < len; i++){
            if (!map.containsKey(array[i])) {
                map.put(array[i], 1);
            } else {
                int count = map.get(array[i]) + 1;
                map.remove(array[i]);
                map.put(array[i], count);
            }
        }
        
        Iterator<Map.Entry<Integer, Integer>> it = map.entrySet().iterator();
        while(it.hasNext()) {
            Map.Entry<Integer, Integer> entry = it.next();
            int key = entry.getKey();
            int val = entry.getValue();
            if (val > len / 2) {
                return key;
            }
        }
        return 0;
    }
}
  • 这个HashMap的迭代使用起来有点麻烦,可以参考下面这个blog查看使用方法:
  • (Java中Map的 entrySet() 详解以及用法(四种遍历map的方式)
  • 使用HashMap要引入三个包:
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
  • 进行迭代的时候指定迭代器的数据类型:Iterator<Map.Entry<Integer, Integer>>
  • 获得map的迭代器:map.entrySet().iterator();
  • 进行迭代,是否有下一个的判断hasNext()方法。
  • 得到键值对:Map.Entry<Integer, Integer> entry = it.next()
    int key = entry.getKey()
    int value = entry.getValue()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值