【Leetcode刷题篇】leetcode169 多数元素
发布日期:2021-06-29 15:34:09 浏览次数:3 分类:技术文章

本文共 886 字,大约阅读时间需要 2 分钟。

给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。

你可以假设数组是非空的,并且给定的数组总是存在多数元素。

示例 1:

输入: [3,2,3]
输出: 3

示例 2:

输入: [2,2,1,1,1,2,2]
输出: 2

解题思路一、用hashmap来解题

package com.lcz.leetcode;/** * 多数元素 * @author LvChaoZhang * */import java.util.*;public class Leetcode169 {
class Solution {
public int majorityElement(int[] nums) {
// 用hashmap来解题 HashMap
hashMap = new HashMap<>(); for(int i=0;i
> 1; // 结果存放 Map.Entry
res = null; // 对hashMap进行遍历 for(Map.Entry
entry:hashMap.entrySet()) {
if(res==null || entry.getValue()>res.getValue()) {
res = entry; } } return res.getKey(); } }}

解题思路二、用排序 算法来解题

class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums); return nums[nums.length / 2]; }}

转载地址:https://codingchaozhang.blog.csdn.net/article/details/110456112 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:【Java网络编程与IO流】Apache Tomcat和Nginx的区别是什么?
下一篇:【Leetcode刷题篇】leetcode160 相交链表

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2024年04月10日 09时22分00秒