You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
class Solution { public void rotate(int[][] matrix) { int m = matrix.length, n = matrix[0].length; int[][] visited = new int[m][n]; for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ if(visited[i][j] == 1) continue; int x = i, y = j; int value = matrix[i][j]; while(true){ int s = n-1-x, t = y; if(visited[t][s] == 1) break; int temp = matrix[t][s]; matrix[t][s] = value; value = temp; visited[t][s] = 1; x = t; y = s; } } } } }
Solution 2
此方法类似Solution 1,但是并非原地算法。
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { publicvoidrotate(int[][] matrix) { intm= matrix.length, n = matrix[0].length; int[][] mat = newint[m][n]; for(inti=0; i < m; i++){ for(intj=0; j < n; j++){ ints= n-1-i, t = j; mat[t][s] = matrix[i][j]; } } for(inti=0; i < m; i++){ for(intj=0; j < n; j++){ matrix[i][j] = mat[i][j]; } } } }
Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.
You must solve this problem without using the library’s sort function.
You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.
Merge nums1 and nums2 into a single array sorted in non-decreasing order.
The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.