深圳微信网站建设公司哪家好seo蜘蛛屯
LeetCode189_189. 轮转数组
一、描述
给定一个整数数组 nums,将数组中的元素向右轮转 k 个位置,其中 k 是非负数。
示例 1:
输入: nums = [1,2,3,4,5,6,7], k = 3
输出: [5,6,7,1,2,3,4]
解释:
向右轮转 1 步: [7,1,2,3,4,5,6]
向右轮转 2 步: [6,7,1,2,3,4,5]
向右轮转 3 步: [5,6,7,1,2,3,4]
示例 2:
输入:nums = [-1,-100,3,99], k = 2
输出:[3,99,-1,-100]
解释:
向右轮转 1 步: [99,-1,-100,3]
向右轮转 2 步: [3,99,-1,-100]
提示:
1 <= nums.length <= 105
-231 <= nums[i] <= 231 - 1
0 <= k <= 105
二、题解
方法:
import java.util.Arrays;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;/*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]
Note:Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
Could you do it in-place with O(1) extra space?*//*** 189. Rotate Array** 题意:将一个数组循环右移数组中的元素k次。* 思路: 1、定义一个队列存放nums中的每个元素。* 2、因为是将最后的一个元素拿到前面k次,因为队列只能从头取,所以可以考虑将前面的每个元素往后移动nums.length-k%(nums.length)次,* 因为k可能大于nums.length,所以使用k%(nums.length)。* 3、将队列中的元素重新存放到nums中即可。*/
public class LeetCode189 {public static void main(String[] args) {Solution189 s189 = new Solution189();int[] nums = {1, 2, 3, 4, 5, 6, 7};int[] nums2 = {-1, -100, 3, 99};int[] nums3 = {1, 2, 3};int k = 3;int k2 = 2;int k3 = 4;s189.rotate2(nums3, k3);}
}class Solution189 {//使用队列思想//AC Your runtime beats 4.10 % of java submissions.//34 / 34 test cases passed. Status: Accepted Runtime: 13 mspublic void rotate2(int[] nums, int k) {// 定义一个队列(阻塞队列)用来存放A中的每个元素BlockingQueue<Integer> queue = new LinkedBlockingQueue<Integer>();for (int i = 0; i < nums.length; i++) {try {queue.put(nums[i]);} catch (InterruptedException e) {e.printStackTrace();}}//System.out.println("queue: " + queue);int size = queue.size();//注意使用k%size,以为k有可能大于sizefor (int i = 0; i < size - k % size; i++) {//注意这里的size一定要在外面定义一个变量存储,否则每次循环都会变!Integer temp = queue.poll();//取出来对头queue.offer(temp);//把原来的对头放到队尾}System.out.println("修改后queue: " + queue);for (int i = 0; i < size; i++) {nums[i] = queue.poll();}//System.out.println(Arrays.toString(nums));}}
LeetCode 100. 相同的树
LeetCode 101. 对称二叉树
LeetCode 102. 二叉树的层序遍历
LeetCode 103. 二叉树的锯齿形层序遍历
LeetCode 104. 二叉树的最大深度
LeetCode 105. 从前序与中序遍历序列构造二叉树
LeetCode 107. 二叉树的层序遍历 II
LeetCode 108. 将有序数组转换为二叉搜索树
LeetCode 121. 买卖股票的最佳时机
LeetCode 122. 买卖股票的最佳时机 II
LeetCode 136. 只出现一次的数字
LeetCode 167. 两数之和 II - 输入有序数组
LeetCode 189. 轮转数组
LeetCode 190. 颠倒二进制位
LeetCode 191. 位1的个数
声明:
题目版权为原作者所有。文章中代码及相关语句为自己根据相应理解编写,文章中出现的相关图片为自己实践中的截图和相关技术对应的图片,若有相关异议,请联系删除。感谢。转载请注明出处,感谢。
By luoyepiaoxue2014
B站: https://space.bilibili.com/1523287361 点击打开链接
微博: http://weibo.com/luoyepiaoxue2014 点击打开链接