Majority Element 题目:
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
本题就是为了寻找数组中出现次数超过n/2的数字。一种最简单的思路就是将数组排序,然后判断i和i+n/2是否相等即可。代码入下:
public int majorityElement(int[] nums) {
Arrays.sort(nums);
for(int i=0; i<nums.length; i++){
if(nums[i] == nums[i+nums.length/2])
return nums[i];
}
return 0;
}
这种方法因为使用了排序,而导致效率较低。由于存在某个数出现的次数大于n/2,比其他数字出现次数之和还要打。所以我们可以使用下面这种方法来求解。代码入下:
public int majorityElement1(int[] num) {
int major=num[0], count = 1;
for(int i=1; i<num.length;i++){
if(count==0){
count++;
major=num[i];
}else if(major==num[i]){
count++;
}else count--;
}
return major;
}
Rotate Array 题目:
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
本题是实现数组反转的功能。第一种思路就是使用一个大小为tmp的数组来保存后k个数,然后将前面的n-k个数存到后面,最后再把tmp的k个数保存到前面即可。代码入下所示:
public void rotate(int[] nums, int k) {
if(nums.length <= 1){
return;
}
int step = k % nums.length;
int [] tmp = new int[step];
for(int i=0; i<step; i++)
tmp[i] = nums[nums.length-step+i];
for(int i=nums.length-step-1; i>=0; i--)
nums[i+step] = nums[i];
for(int i=0; i<step; i++)
nums[i] = tmp[i];
}
另外一种思路就是将数组的前面n-k个数反转,再将后面k个数反转,在将数组反转,就可以得到结果。比如[1,2,3,4,5,6,7], k=3. 先变成[4,3,2,1,5,6,7], 再变成[4,3,2,1,7,6,5],最后再翻转变成[5,6,7,1,2,3,4]. 这种方法的代码如下》
public void rotate1(int[] nums, int k) {
if(nums.length <= 1){
return;
}
//step each time to move
int step = k % nums.length;
reverse(nums,0,nums.length - 1);
reverse(nums,0,step - 1);
reverse(nums,step,nums.length - 1);
}
//reverse int array from n to m
public void reverse(int[] nums, int n, int m){
while(n < m){
nums[n] ^= nums[m];
nums[m] ^= nums[n];
nums[n] ^= nums[m];
n++;
m--;
}
}