多数元素 and 轮转数组

This commit is contained in:
Zerroi 2024-03-05 19:43:29 +08:00
parent af3f2544bf
commit 9b4e1b906d
2 changed files with 108 additions and 0 deletions

View File

@ -0,0 +1,61 @@
package com.zerroi.leetcode.ThreeFive;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class MajorityElement {
public static void main(String[] args) {
Solution solution = new Solution();
int[] nums = new int[]{2, 2, 1, 1, 1, 2, 2};
int res = solution.majorityElement(nums);
// System.out.println("res = " + res);
// System.out.println(5/2);
}
}
/**
* 给定一个大小为 n 的数组 nums 返回其中的多数元素多数元素是指在数组中出现次数 大于 n/2 的元素
* 你可以假设数组是非空的并且给定的数组总是存在多数元素
*/
class Solution {
public int majorityElement(int[] nums) {
// 用HashMap key->元素 value->元素出现的次数
Map<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
if (map.containsKey(num)) {
map.put(num, map.get(num) + 1);
} else {
map.put(num, 1);
}
}
for (Integer key : map.keySet()) {
if (map.get(key) > nums.length / 2) {
return key;
}
}
return 0;
}
public int majorityElementSort(int[] nums) {
Arrays.sort(nums);
return nums[nums.length / 2];
}
public int majorityElementVote(int[] nums) {
int winner = nums[0];
int count = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] == winner) {
count++;
} else if (count == 0) {
winner = nums[i];
count++;
} else {
count--;
}
}
return winner;
}
}

View File

@ -0,0 +1,47 @@
package com.zerroi.leetcode.ThreeFive;
import java.util.Arrays;
/**
* 给定一个整数数组 nums将数组中的元素向右轮转 k 个位置其中 k 是非负数
*/
public class Rotate {
public static void main(String[] args) {
}
}
class SolutionSecond {
public void rotate(int[] nums, int k) {
k = k % nums.length;
int[] temp = new int[k];
for (int i = 0; i < k; i++) {
temp[i] = nums[nums.length - k + i];
}
for (int i = nums.length - k; i >= 0; i--) {
nums[i + k] = nums[i];
}
for (int i = 0; i < k; i++) {
nums[i] = temp[i];
}
}
public void rotateReverse(int[] nums, int k) {
k = k % nums.length;
reverse(nums, 0, nums.length);
reverse(nums, 0, k - 1);
reverse(nums, k, nums.length);
}
public void reverse(int[] nums, int start, int end) {
while (start < end) {
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start += 1;
end -= 1;
}
}
}