leetcode 581. Shortest Unsorted Continuous Subarray Add to List
給定一個整數(shù)數(shù)組窒升,找出其中最短的一段連續(xù)子數(shù)組,當對這段子數(shù)組排序后家淤,整個數(shù)組遞增有序异剥。
Input: [2, 6, 4, 8, 10, 9, 15]
Output: 5
你只需將[6, 4, 8, 10, 9]按升序排列就可以讓整個數(shù)組都是升序排列瑟由。
注意:
數(shù)組長度范圍[1, 10000]
輸入數(shù)組可能包含重復絮重,因此“遞增有序”意思是<=
解題思路:先把數(shù)組進行排序,然后再將輸入的數(shù)組和排序過后的數(shù)組進行對比歹苦。左右同時對比青伤,左右比較最先不同的下標就是子序列的邊界。
[2, 6, 4, 8, 10, 9, 15]
[2, 4, 6, 8, 9, 10,15 ]
左邊開始不同的是(4殴瘦,6)下標是1
右邊開始不同的是(9狠角,10)下表是5
length(1,5)= 5
#java
public class Solution {
public int findUnsortedSubarray(int[] nums) {
int temp[] = new int[nums.length];
System.arraycopy(nums, 0, temp, 0, nums.length);
Arrays.sort(temp);
int start = 0;
int end = nums.length-1;
while(start<nums.length&&nums[start]==temp[start]){
start++;
}
while(end>=0&&nums[end]==temp[end]){
end--;
}
if(end>start){
return end-start+1;
}else{
return 0;
}
}
}```
ref:
http://bookshadow.com/weblog/2017/05/15/leetcode-shortest-unsorted-continuous-subarray/
http://www.reibang.com/p/093c2116b749
https://leetcode.com/problems/shortest-unsorted-continuous-subarray/#/description
Java拷貝數(shù)組的幾種方法:
http://www.cnblogs.com/jjdcxy/p/5870524.html
####leetcode 566. Reshape the Matrix
In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new one with different size but keep its original data. You're given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were. If the 'reshape' operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.
Example 1:
Input:
nums =
[[1,2],
[3,4]]
r = 1, c = 4
Output:
[[1,2,3,4]]
Explanation:
The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.
Example 2:
Input:
nums =
[[1,2],
[3,4]]
r = 2, c = 4
Output:
[[1,2],
[3,4]]
Explanation:
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.
Note:
The height and width of the given matrix is in range [1, 100].
The given r and c are all positive.
解題思路:太簡單了蚪腋,沒思路丰歌。
public class Solution {
public int[][] matrixReshape(int[][] nums, int r, int c) {
int colum = nums[0].length;
int row = nums.length;
int[][] temp = new int[r][c];
if((columrow)!=(rc)){
return nums;
}else{
for(int i = 0;i<row*colum;i++){
temp[i/c][i%c]=nums[i/colum][i%colum];
}
return temp;
}
}
}