A题
class Solution {
public int maximizeSum(int[] nums, int k) {
Arrays.sort(nums);
return (2*nums[nums.length-1]+k-1)*k/2;
}
}
B题
class Solution {
public int[] findThePrefixCommonArray(int[] A, int[] B) {
int n =A.length;
int[] c = new int[n];
Set<Integer> s = new HashSet<Integer>();
for(int i=0;i<n;i++){
s.add(A[i]);
for(int j=0;j<=i;j++){
if(s.contains(B[j])){
c[i]++;
}
}
}
return c;
}
}
C题
class Solution {
int sum=0;
int[][] vis;
int[] dx = {0,1,0,-1};
int[] dy= {1,0,-1,0};
int m,n;
int max=0;
public int findMaxFish(int[][] grid) {
m =grid.length;
n =grid[0].length;
vis = new int[m][n];
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(grid[i][j]!=0){
sum=0;
initialize(vis);
dfs(i,j,grid);
max=Math.max(max,sum);
}
}
}
return max;
}
public void dfs(int x,int y,int[][] grid){
sum+=grid[x][y];
vis[x][y]=1;
for(int k=0;k<4;k++){
int tx = x+dx[k];
int ty = y+dy[k];
if(tx>=0&&tx<m&&ty>=0&&ty<n&&vis[tx][ty]==0&&grid[tx][ty]!=0){
dfs(tx,ty,grid);
}
}
return;
}
public void initialize(int[][] vis){
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
vis[i][j]=0;
}
}
return;
}
}
D题
class Solution {
int[] tree;
int lowbit(int x){
return x&-x;
}
int query(int x){
int ans=0;
for(int i=x;i>0;i-=lowbit(i))ans+=tree[i];
return ans;
}
void add(int x, int u) {
for (int i = x; i <= n; i += lowbit(i)) tree[i] += u;
}
int n;
public long countOperationsToEmptyArray(int[] nums) {
n=nums.length;
long ans =n;
tree=new int[n+1];
int[][] arr = new int[n][2];
for(int i=0;i<n;i++){
arr[i][0]=nums[i];
arr[i][1]=i;
}
Arrays.sort(arr, Comparator.comparingInt(a -> a[0]));
ans+=arr[0][1];
int loc =arr[0][1]+1;
add(loc,1);
for(int i=1;i<n;i++){
int newLoc = arr[i][1]+1;
int s=0;
if(newLoc>loc){
s=(newLoc-loc-1-(query(newLoc)-query(loc)));
}else {
s=(n-loc-1-(query(n)-query(loc)))+(newLoc-(query(newLoc)));
}
ans+=s;
loc=newLoc;
add(newLoc,1);
}
return ans;
}
}