# Algorithm interview question 2: rotating array, there are repeated elements, and the number appears only once

Time：2022-5-9

Here is a personal solution to rotating arrays, duplicate elements and numbers that appear only once ### Topic 1: rotating array

``Given an array, move the elements in the array K positions to the right, where k is a non negative number.``

``````Think of as many solutions as possible, and there are at least three different ways to solve this problem.
Can you use the in-situ algorithm with spatial complexity O (1) to solve this problem?``````

### Example 1:

``````Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
Rotate one step 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: num = [- 1, - 100,3,99], k = 2
Output: [3,99, - 1, - 100]
Explanation:
Rotate 1 step to the right: [99, - 1, - 100,3]
Rotate 2 steps to the right: [3,99, - 1, - 100]``````

### Tips:

``````1 <= nums.length <= 2 * 104
-231 <= nums[i] <= 231 - 1
0 <= k <= 105``````

``````/**
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/
var rotate = function(nums, k) {
if(nums.length == 1 || k == 0){
return nums
}
if(k > nums.length){
k = k%nums.length
}
k = nums.length - k;
for(let ii=0;ii``````

### Topic 2: there are duplicate elements

``````Given an integer array, determine whether there are duplicate elements.

If a value exists and appears in the array at least twice, the function returns true. If each element in the array is different, false is returned.``````

### Example 1:

``````Input: [1,2,3,1]
Output: true``````

### Example 2:

``````Input: [1,2,3,4]
Output: false``````

### Example 3:

``````Input: [1,1,1,3,3,4,3,2,4,2]
Output: true``````

``````/**
* @param {number[]} nums
* @return {boolean}
*/
var containsDuplicate = function(nums) {
let bind = false;
var arr = nums.sort();
for(let i=0;i``````

``````/**
* @param {number[]} nums
* @return {boolean}
*/
var containsDuplicate = function(nums) {
let bind = false;
for(let i=0;i``````

### Topic 3: numbers that appear only once

``Given a non empty array of integers, each element appears twice except that one element appears only once. Find the element that appears only once.``

explain:

``Your algorithm should have linear time complexity. Can you do it without using extra space?``

Example 1:

``````Input: [2,2,1]
Output: 1``````

Example 2:

``````Input: [4,1,2,1,2]
Output: 4``````

``````/**
* @param {number[]} nums
* @return {number}
*/
var singleNumber = function(nums) {
nums = nums.sort();
if(nums.length == 1){
return nums;
}
let value = null;
for(let i=0;i``````

``````var singleNumber = function(nums) {