leetcode:数组(easy)

leetcode 581. Shortest Unsorted Continuous Subarray Add to List

给定一个整数数组,找出其中最短的一段连续子数组,当对这段子数组排序后,整个数组递增有序。

Input: [2, 6, 4, 8, 10, 9, 15]
Output: 5
你只需将[6, 4, 8, 10, 9]按升序排列就可以让整个数组都是升序排列。

注意:
数组长度范围[1, 10000]
输入数组可能包含重复,因此“递增有序”意思是<=

解题思路:先把数组进行排序,然后再将输入的数组和排序过后的数组进行对比。左右同时对比,左右比较最先不同的下标就是子序列的边界。

[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=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.jianshu.com/p/093c2116b749
https://leetcode.com/problems/shortest-unsorted-continuous-subarray/#/description
Java拷贝数组的几种方法:
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 temp[i/c][i%c]=nums[i/colum][i%colum];
}
return temp;
}
}
}

你可能感兴趣的:(leetcode:数组(easy))