BiliBili three programming questions
The first problem is to find a continuous array of 1
Idea: Solve directly with violence
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param arr int整型一维数组
* @param k int整型 允许0变为1的个数
* @return int整型
*/
public static int GetMaxConsecutiveOnes (int[] arr, int k) {
// write code here
int maxV = -1;
int numZeros;
for(int i=0; i<arr.length; i++){
for(int j=i; j<arr.length; j++){
numZeros = getZeros(Arrays.copyOfRange(arr,i,j-i+1));
if(numZeros <= k){
maxV = Math.max(maxV,getSum(Arrays.copyOfRange(arr,i,j-i+1))+numZeros);
}
}
}
return maxV;
}
private static int getSum(int[] arr){
int sum=0;
for(int i=0; i<arr.length; i++){
sum+=arr[i];
}
return sum;
}
private static int getZeros(int[] arr){
int count=0;
for(int i=0; i<arr.length; i++){
if(arr[i]==0){
count++;
}
}
return count;
}
public static void main(String[] args) {
int[] arr = new int[]{
1,1,1,0,0,1};
int res = GetMaxConsecutiveOnes(arr,2);
System.out.println(res);
}
}
The second question rotates the print array leetcode original question
Idea: Set the boundary of the ranks and gradually shrink
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param matrix int整型二维数组
* @return int整型一维数组
*/
public int[] SpiralMatrix (int[][] matrix) {
// write code here
int rows = matrix.length;
int cols = matrix[0].length;
int[] res = new int[rows*cols];
if(rows==0||cols==0) return res;
int up = 0, down = rows-1, left = 0, right = cols-1;
int i = 0;
while(i<rows*cols){
for(int col=left; col<=right;col++) {
res[i] = matrix[up][col];i++;}
up++;
for(int row=up; row<=down;row++) {
res[i] = matrix[row][right];i++;}
right--;
for(int col=right; col>=left;col--) {
res[i] = matrix[down][col];i++;}
down--;
for(int row=down; row>=up;row--) {
res[i] = matrix[row][left];i++;}
left++;
}
return res;
}
}
The third question is the average number of pieces
Idea: Use an int variable to store the number of times and store it in the list (I don’t know what boundary conditions are not considered, a is 87.5, is there the same?)
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param str string字符串
* @return int整型
*/
public int GetFragment (String str) {
// write code here
ArrayList<Integer> list = new ArrayList<>();
int cnt = 1;
if(str.length()<=1) return str.length();
if(str.length()>=2 && str.charAt(0)!=str.charAt(1)) list.add(cnt);
for(int i=1; i<str.length(); i++){
if(str.charAt(i)==str.charAt(i-1)){
cnt++;
if(i==(str.length()-1)){
list.add(cnt);
break;
}
}
else{
list.add(cnt);
cnt=1;
if(i==(str.length()-1)){
list.add(cnt);
break;
}
}
}
int sum = 0;
for(int v:list){
sum+=v;
}
return sum/(list.size());
}
}