leetcode刷题23天
189. Rotate Array
Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2:
Input: [-1,-100,3,99] and k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
代码1(想法比较简单粗暴,时间复杂度比较高):
public static void rotate(int[] nums, int k) {
if(nums.length==0||k==0)
return;
for(int i =1;i<=k;i++) {
int temp = nums[nums.length-1];
for(int j = nums.length-1;j>0;j--) {
nums[j] =nums[j-1];
}
nums[0] = temp;
}
for(int i = 0;i<nums.length;i++) {
System.out.print(nums[i]+" ");
}
}
代码2(看了一个解答以后得到的,想法确实很新颖,相比上一个方案,时间复杂度减少很多):
class Solution {
public static void rotate(int[] nums, int k) {
if(nums.length==0||k==0)
return;
k = k%nums.length;
reverseArr(nums,0,nums.length-k-1);
reverseArr(nums,nums.length-k,nums.length-1);
reverseArr(nums,0,nums.length-1);
}
public static void reverseArr(int[] nums,int start,int end) {
int tempValue;
while(start<end) {
tempValue = nums[start];
nums[start] = nums[end];
nums[end] = tempValue;
start++;
end--;
}
}
}
- Reverse Bits
Reverse bits of a given 32 bits unsigned integer.
Example 1:
Input: 00000010100101000001111010011100
Output: 00111001011110000010100101000000
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.
Example 2:
Input: 11111111111111111111111111111101
Output: 10111111111111111111111111111111
Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10101111110010110010011101101001.
代码:
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
if(n==0)
return 0;
int res = 0;
for(int i = 1;i<=32;i++) {
res = res<<1 | (n & 1);
n=n>>>1;
}
return res;
}
}