Java 获取二维整数数组中的最长序列
我陷入这个问题已经有一段时间了。目标是返回重复序列最长的Arraylist。如果我有Java 获取二维整数数组中的最长序列,java,arrays,arraylist,Java,Arrays,Arraylist,我陷入这个问题已经有一段时间了。目标是返回重复序列最长的Arraylist。如果我有 int[][] a = {{ 1, 1, 3, 4 } { 2, 2, 2, 1} { 3, 3, 3, 3} { 0, 0, 1, 1}}; 方法longestSequence()应返回[3,3,3,3]的数组列表,因为3具有最长的序列。我只能水平地找到序列。请告诉我我做错了什么 int[][] a = {{ 1, 1, 3
int[][] a = {{ 1, 1, 3, 4 }
{ 2, 2, 2, 1}
{ 3, 3, 3, 3}
{ 0, 0, 1, 1}};
方法longestSequence()
应返回[3,3,3,3]
的数组列表,因为3
具有最长的序列。我只能水平地找到序列。请告诉我我做错了什么
int[][] a = {{ 1, 1, 3, 4 }
{ 2, 2, 2, 1}
{ 3, 3, 3, 3}
{ 0, 0, 1, 1}};
public List<Integer> longestSequence(int[][]a){
int count = 1, max = 1;
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < a.length; i++)
for(int j = 1; j < a[i].length; j++) {
if (a[i][j] >= a[i][j-1]) {
count++;
list.add(a[i][j]);
} else {
if (count > max) {
max = count;
}
list.clear();
count = 1;
}
}
return list;
}
int[]a={{1,1,3,4}
{ 2, 2, 2, 1}
{ 3, 3, 3, 3}
{ 0, 0, 1, 1}};
公共列表最长序列(int[]a){
整数计数=1,最大值=1;
列表=新的ArrayList();
for(int i=0;i=a[i][j-1]){
计数++;
增加(a[i][j]);
}否则{
如果(计数>最大值){
最大值=计数;
}
list.clear();
计数=1;
}
}
退货清单;
}
您的实现存在一些问题。因此,除了二维数组的创建之外,即使当前序列不是最大序列,也要继续覆盖结果列表。所以要解决这个问题,请保留一个本地arrayList来保存当前序列,并且仅当它大于最大值时才将其分配给结果
int[][] a = {{ 1, 1, 3, 4 },
{ 2, 2, 2, 1},
{ 3, 3, 3, 3},
{ 0, 0, 1, 1}};
public List<Integer> longestSequence(int[][]a){
int count = 1, max = 1;
List<Integer> result = new ArrayList<Integer>();
for (int i = 0; i < a.length; i++) {
List<Integer> current = new ArrayList<Integer>();
for(int j = 1; j < a[i].length; j++) {
if (a[i][j] >= a[i][j-1]) {
count++;
current.add(a[i][j]);
} else{
if (count > max) {
max = count;
result = current;
}
current = new ArrayList<Integer>();
count = 1;
}
}
}
return result ;
}
int[]a={{1,1,3,4},
{ 2, 2, 2, 1},
{ 3, 3, 3, 3},
{ 0, 0, 1, 1}};
公共列表最长序列(int[]a){
整数计数=1,最大值=1;
列表结果=新建ArrayList();
for(int i=0;i=a[i][j-1]){
计数++;
现加(a[i][j]);
}否则{
如果(计数>最大值){
最大值=计数;
结果=电流;
}
当前=新的ArrayList();
计数=1;
}
}
}
返回结果;
}
问题似乎在于您没有正确地清除列表,并且没有保留最佳列表作为要返回的值
您可以保留一个maxList
,即与运行长度max
相对应的元素列表:
max = count; maxList = new ArrayList<>(list);
您的2d数组错误。元素之间需要逗号@KumarSaurabh的可能重复项,该方法需要返回最长的序列,而不是构造2d数组。您在每次迭代后都要清除列表。您可以检查该项是否为
=
,但您只需要=
。您能告诉我们它的作用,并解释其错误原因吗?它返回一个空列表@Amr@John我现在修复了它再次检查:)所以我需要两个列表?一个是max,一个是临时列表@对于当前的方法,您需要两个列表。我已经用避免在搜索过程中创建任何列表的代码更新了答案。
int bestValue = -1;
int bestLength = 0;
for (int i = 0; i < a.length; ++i) {
int[] row = a[i];
int j = 0;
while (j < row.length) {
int start = j++;
while (j < row.length && row[j] == row[start]) j++;
if (j-start > bestLength) {
bestLength = j - start;
bestValue = row[start];
}
}
}
return Collections.nCopies(bestLength, bestValue);