Leetcode刷题
数组系列每日三题(两简单、一中等)
PS:题目前面都有该题的网址链接,先看懂题目,再来看解题思路;不然很容易看不懂的,尤其是刚刷题的新手
1.转置矩阵 https://leetcode-cn.com/problems/transpose-matrix/
class Solution {
public int[][] transpose(int[][] A) {
int rowNums = A.length,colNums = A[0].length;
int[][] B = new int[colNums][rowNums];
for(int i = 0 ; i < rowNums ; i++){
for(int j = 0 ; j < colNums ; j++){
B[j][i] = A[i][j];
}
}
return B;
}
}
执行用时: **0 ms**
内存消耗: **39.3 MB**
解释下子我的解题方法
将矩阵的主对角线翻转,交换矩阵的 行索引和列索引 即可
PS:新手在学JAVASE基础时应该会讲例题关于数组的各种翻转、对角线的题目
这题比较简单,简单看下代码就行,过了过了
2.计数质数 https://leetcode-cn.com/problems/count-primes/
class Solution {
public int countPrimes(int n) {
boolean[] a = new boolean[n];
Arrays.fill(a,true);
for(int i = 2; i * i < n;i ++){
if(a[i]){
for(int j = i * i ; j < n ; j += i){
a[j] = false;
}
}
}
int count = 0;
for(int i = 2 ; i < n ; i++){
if(a[i]) count++;
}
return count;
}
}
执行用时: **15 ms**
内存消耗: **37.1 MB**
解释下上面代码思路
for(int i = 2; i * i < n;i ++){
if(a[i]){
for(int j = i * i ; j < n ; j += i){
a[j] = false;
}
}
}
这里是已经优化好了的两重循环,乍一看可能以为时间复杂度是O(n),其实不然 ,为n*loglogn
来张图片解释,或者自己再比划比划。
目前讲解题目的手段先以此方式,日后再加以改正
3.盛最多水的容器 https://leetcode-cn.com/problems/container-with-most-water/
class Solution {
public int maxArea(int[] height) {
int area = 0;
int left = 0,right = height.length - 1;
while(left < right){
int h = Math.min(height[left],height[right]);
area = Math.max(area,h*(right - left));
if(height[left] < height[right]){
left++;
}else if(height[left] > height[right]){
right--;
}else{
left++;
right--;
}
}
return area;
}
}
执行用时: **4 ms**
内存消耗: **40.2 MB**
解释一番
看题目可以通俗地知道是求其最大面积,最优解法是用双指针
左右指针作为容器边界的所有位置的范围,一开始设左指针left=0
,右指针right=height.length - 1
,
当left<right
时,保证指针不重复指向
面积=长*高,即高=heigth[left]
或者高=heigth[right]
,因为没有确定左右哪边更高;则长=高-矮 之间的长度 即可
总而言之,这三道题目是自己做得比较顺手的题目
新手新手,不久前刚开练,如有更好的建议或者解法,欢迎探讨