当前位置:网站首页>Leetcode sword finger offer brush questions - day 23
Leetcode sword finger offer brush questions - day 23
2022-07-02 08:53:00 【DEGv587】
Leetcode The finger of the sword Offer How to brush questions :
The finger of the sword Offer 39. A number that appears more than half the times in an array
Solution 1 : Sort library function + Median
class Solution {
public int majorityElement(int[] nums) {
if (nums.length == 0) return -1;
Arrays.sort(nums);
return nums[nums.length / 2];
}
}Solution 2 :hashmap
class Solution {
public int majorityElement(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
for (int n : nums) {
map.put(n, map.getOrDefault(n, 0) + 1);
if (map.get(n) > (nums.length / 2)) {
return n;
}
}
return -1;
}
}Solution 3 : Moore voting , Limit for limit , Left to the end is more than half
class Solution {
public int majorityElement(int[] nums) {
int count = 0, ret = 0;
for (int n : nums) {
if (count == 0) {
ret = n;
++count;
} else {
count = ret == n ? ++count : --count;
}
}
return ret;
}
}The finger of the sword Offer 66. Building a product array
solution : From left to right , Then multiply from right to left
class Solution {
public int[] constructArr(int[] a) {
int len = a.length;
int[] ret = new int[len];
// From left to right
int cur = 1;
for (int i = 0; i < len; ++i) {
ret[i] = cur;
cur *= a[i];
}
// From right to left
cur = 1;
for (int i = len - 1; i >= 0; --i) {
ret[i] *= cur;
cur *= a[i];
}
return ret;
}
}边栏推荐
猜你喜欢
随机推荐
[blackmail virus data recovery] suffix Crylock blackmail virus
HCIA—應用層
Openfeign is easy to use
commands out of sync. did you run multiple statements at once
Minecraft安装资源包
QT drag event
Service de groupe minecraft
统计字符串中各类字符的个数
Qt QTimer类
Kubernetes deploys Loki logging system
Minecraft空岛服开服
整理秒杀系统的面试必备!!!
Introduction to the basic concept of queue and typical application examples
Minecraft install resource pack
Sqli labs level 8 (Boolean blind note)
HCIA—数据链路层
Sentinel 简单使用
Detailed explanation of NIN network
HackTheBox-Gunship
C language custom type enumeration, Union (clever use of enumeration, calculation of union size)









