力扣面试经典150题day3第五题(lc69),第六题(lc189)
文章目录
- 一、lc169
- 1.排序做法
- 2.灵神做法 打擂台
- 二、lc189
- 1.引入额外数组
- 2.原地翻转
一、lc169
1.排序做法
因为众数的定义为出现次数大于(n/2),所以数组长度一半位置的元素一定为众数,可以不用进行遍历计数,统计出众数(不用排序也计数统计出众数,但需要利用map保存是哪个元素的数目,排序后不需要,所有相同的元素排在一起了,只需遍历完一个元素的数目后,与n/2进行比较即可)
class Solution {public int majorityElement(int[] nums) {Arrays.sort(nums);return nums[nums.length / 2];}
}
2.灵神做法 打擂台
nums[0]先做为擂主,初始血量为1,遍历后面元素,遇到同门(相同元素),血量加1,遇到对手(不同元素),血量减1,当血量为0时,换当前位置元素为擂主,遍历完后擂主的为众数。严格证明可以看代码下面的链接
class Solution {public int majorityElement(int[] nums) {int ans = 0;int hp = 0;for (int x : nums) {if (hp == 0) { // x 是初始擂主,生命值为 1ans = x;hp = 1;} else { // 比武,同门加血,否则扣血hp += x == ans ? 1 : -1;}}return ans;}
}作者:灵茶山艾府
链接:https://leetcode.cn/problems/majority-element/solutions/3744717/on-mo-er-tou-piao-fa-yan-jin-zheng-ming-ww1zv/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
二、lc189
1.引入额外数组
引入额外数组,备份nums数组,再把nums2中(i+k)%n的位置的元素移回nums数组中i的位置把数组看成环形的,右移k,相当于下标+k,由于数组长度为n,i+k大于n时越界了,需要对i+k取模,放在nums数组前面
class Solution {public void rotate(int[] nums, int k) {int n = nums.length;int[] nums2 = new int[n];int tmp;int nex;for(int i = 0;i<n;i++){nums2[i]=nums[i];}for(int i=0;i<n;i++){nex=(i+k)%n;nums[nex]=nums2[i];}}
}
2.原地翻转
class Solution {public void rotate(int[] nums, int k) {int n = nums.length;k %= n; // 轮转 k 次等于轮转 k % n 次reverse(nums, 0, n - 1);reverse(nums, 0, k - 1);reverse(nums, k, n - 1);}private void reverse(int[] nums, int i, int j) {while (i < j) {int temp = nums[i];nums[i++] = nums[j];nums[j--] = temp;}}
}作者:灵茶山艾府
链接:https://leetcode.cn/problems/rotate-array/solutions/2784427/tu-jie-yuan-di-zuo-fa-yi-tu-miao-dong-py-ryfv/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。