java - 如何找到可以通过连接给定数组的所有元素而不使用字符串来构造的最大连接数?
问题描述
实际上,我只是为此添加答案只是为了分享另一种方法,仅此而已。
约束:
1 <= N <= 1000
0 <= ar[i] <= 1000
第一行 N 表示数组中的元素个数
第二行由数组元素组成
例子:
2
100, 9
输出:9100
示例 2:
3
12、13、8
输出:81312
解决方案
此代码不适用于大数字,并且在时间复杂度方面不是有效的解决方案
由于一些误解,我的帖子被删除了,请考虑这是我的问题,我的解决方案只是因为有人建议编辑答案被添加到问题中作为“到目前为止我的代码:”
import java.io.*;
import java.util.*;
public class Solution
{
static long ans=0;
public static void main(String[] args)
{
int N,count=0;
long n;
Scanner scan=new Scanner(System.in);
N=scan.nextInt();
long[] ar=new long[N];
long[] vis=new long[N];
for(int i=0;i<N;i++)
{
ar[i]=scan.nextLong();
vis[i]=0;
n=ar[i];
while(n!=0)
{
n/=10;
count++;//It counts the number of digits of all elements in the given array
}
}
int index=0;
long val=0,a=0;
int x=0;
recur(ar,vis,index,N,count,val,a);
System.out.println(ans);
}
static void recur(long ar[],long vis[],int index,int N,int count,long val,long a)
{
if(index==N)
{
ans=Math.max(ans,val);
return;
}
for(int i=0,j=0;i<N;i++,j++)
{
if(vis[i]==0)
{
vis[i]=1;
a=counter(ar[i]);//counter returns no. of digits in the current element
count-=a;//this returned value is subtracted from the count(which is the number of digits of all elements in the array)
val+=ar[i]*(Math.pow(10,count));// now the corresponding digit's place is multiplied with the element to make up the number
recur(ar,vis,index+1,N,count,val,a);
vis[i]=0;
val-=ar[i]*(Math.pow(10,count));
count+=a;
}
}
}
static long counter(long val)
{
int count=0;
while(val!=0)
{
val/=10;
count++;
}
return count;
}
}
推荐阅读
- postgresql - 如何使用'?在@Query 中?如何在 spring-boot 中使用 postgres 的 Jsonb?
- android - translationZ 在我的带有地图片段的 ConstraintLayout 中不起作用
- sql - 查询优化:拆分时慢查询更快
- arrays - 用于跟踪过去 4 周内事件发生次数的 Google 表格公式
- c# - C# Foreach 循环,帮助实现移动到 NEXT 和 PRIVIOUS 步骤
- c++ - 模板类中的模板函数
- r - 我不知道 R,我想用给定的 alpha 计算 R 中的 Spearman 相关性,并想知道 p 值
- javascript - 在 JavaScript 中的输入值之后添加文本
- json - 加载 json 文件以触发数据框
- opendj - 如何将自定义属性类型和对象类导入 OpenDJ 3.0?