[英]time limit in Sorted Permutation Rank with Repeats
首先,我想提一下,我不是編程專家。 我正在嘗試解決重復排列的問題,但是我不明白為什么我總是有時間限制。 我的代碼在Java中,並且我正在使用BigInteger進行階乘和其他計算。
請幫助我找出我有時間限制的原因。 我找到了解決問題的相同方法,但是那是在python中。 在這里,我提供了我的代碼。 提前致謝。
import java.math.BigInteger;
public class Solution {
BigInteger factorial(int n){
BigInteger sum=new BigInteger(String.valueOf(1));
if(n<2) return new BigInteger(String.valueOf(n));
for(int j=2;j<=n;j++){
sum=sum.multiply(new BigInteger(String.valueOf(j)));
}
return sum;
}
public int findRank(String a) {
if(a.length()<2) return 1;
Map<Character,Integer> map1=new HashMap<Character,Integer>();
BigInteger sum=new BigInteger(String.valueOf(1));
for(int i=0;i<a.length();i++){
if(!map1.containsKey(a.charAt(i))){
map1.put(a.charAt(i),1);
}
else{
int cc=map1.get(a.charAt(i));
cc=cc+1;
map1.put(a.charAt(i),cc);
}
}
BigInteger temp1=new BigInteger(String.valueOf(1));
for (Map.Entry<Character, Integer> entry : map1.entrySet())
{
temp1=temp1.multiply(new BigInteger(String.valueOf(factorial( entry.getValue()))));
}
temp1=temp1.pow(1000001);
temp1=temp1.mod(new BigInteger(String.valueOf(1000003)));
for(int i=0;i<a.length();i++){
BigInteger rank=new BigInteger(String.valueOf(0));
for(int j=i+1;j<a.length();j++){
if(a.charAt(i)>a.charAt(j)){
rank=rank.add(new BigInteger(String.valueOf(1)));
}
}
BigInteger temp=new BigInteger(String.valueOf(factorial(a.length()-i-1)));
rank=rank.multiply(temp1);
rank=rank.multiply(temp);
sum=sum.add(rank);
sum=sum.mod(new BigInteger(String.valueOf(1000003)));
}
return sum.intValue();
}
}
您使用了過多的字符串解析和對象創建。 這對於運行時來說都是昂貴的。
通過優化使用BigInteger,該方法將在我的機器上在大約1ms內返回。
public class Solution {
private BigInteger factorial(final int n) {
BigInteger sum = BigInteger.ONE;
if (n < 2) {
return BigInteger.valueOf(n);
}
for (int j = 2; j <= n; j++) {
sum = sum.multiply(BigInteger.valueOf(j));
}
return sum;
}
public int findRank(final String a) {
if (a.length() < 2) {
return 1;
}
final Map<Character, Integer> map1 = new HashMap<>();
BigInteger sum = BigInteger.ONE;
for (int i = 0; i < a.length(); i++) {
final char charAt = a.charAt(i);
if (!map1.containsKey(charAt)) {
map1.put(charAt, 1);
} else {
int cc = map1.get(charAt);
map1.put(charAt, cc++);
}
}
BigInteger temp1 = BigInteger.ONE;
for (final Map.Entry<Character, Integer> entry : map1.entrySet()) {
temp1 = temp1.multiply(factorial(entry.getValue()));
}
temp1 = temp1.pow(1000001);
temp1 = temp1.mod(BigInteger.valueOf(1000003));
for (int i = 0; i < a.length(); i++) {
BigInteger rank = BigInteger.ZERO;
for (int j = i + 1; j < a.length(); j++) {
if (a.charAt(i) > a.charAt(j)) {
rank = rank.add(BigInteger.ONE);
}
}
final BigInteger temp = factorial(a.length() - i - 1);
rank = rank.multiply(temp1);
rank = rank.multiply(temp);
sum = sum.add(rank);
sum = sum.mod(BigInteger.valueOf(1000003));
}
return sum.intValue();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.