1.平方数
题目链接:平方数
先将这个数字开根号,找左右两边两个数的平方,看哪个数离这个数近
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner scanner=new Scanner(System.in);
long x =scanner.nextLong();
long s=(long)Math.sqrt(x);
long s1=s*s;
long s2=(s+1)*(s+1);
if(x-s1<s2-x) System.out.println(s1);
else System.out.println(s2);
}
}
2.分组
题目链接:分组
暴力解法
import java.util.*;
public class Main{
public static int n,m;
public static Map<Integer,Integer> hash =new HashMap<>();
public static boolean check(int x){
int g=0;
for(int a:hash.values()){
g+=a/x+(a%x==0?0:1);
}
return g<=m;
}
public static void main(String[] args){
Scanner scanner =new Scanner(System.in);
n=scanner.nextInt();
m=scanner.nextInt();
int hmax=0;
for(int i=0;i<n;i++){
int x=scanner.nextInt();
hash.put(x,hash.getOrDefault(x,0)+1);
hmax=Math.max(hmax,hash.get(x));
}
int kinds=hash.size();
if(kinds>m){
System.out.println(-1);
}else{
for(int i=1;i<=hmax;i++){
if(check(i)){
System.out.println(i);
break;
}
}
}
}
}
二分解法
import java.util.*;
public class Main{
public static int n,m;
public static Map<Integer,Integer> hash =new HashMap<>();
public static boolean check(int x){
int g=0;
for(int a:hash.values()){
g+=a/x+(a%x==0?0:1);
}
return g<=m;
}
public static void main(String[] args){
Scanner scanner =new Scanner(System.in);
n=scanner.nextInt();
m=scanner.nextInt();
int hmax=0;
for(int i=0;i<n;i++){
int x=scanner.nextInt();
hash.put(x,hash.getOrDefault(x,0)+1);
hmax=Math.max(hmax,hash.get(x));
}
int kinds=hash.size();
if(kinds>m){
System.out.println(-1);
}else{
int l=1,r=hmax;
while(l<r){
int mid=(l+r)/2;
if(check(mid))
r=mid;
else{
l=mid+1;
}
}
System.out.println(l);
}
}
}
希望能对大家有所帮助!!!!!