在 ArrayList 中查找数字第 n 次出现的最佳方法是什么?
我已经知道了什么?
- 找到lastIndexOf List接口(interface)中有number方法,在ArrayList类中实现。
- 要找到第一次出现,有 indexOf方法。
我在解决什么问题?
在一个问题中,有一个包含不同数字的列表,我必须返回总和等于目标数字的两个数字的索引。
例如:List = (1,2,1) & target = 2;
现在 1 + 1 =2
答案将是第一个 1 和第二个 1 的索引。
Note: I have solved this problem & I need answer to the question at the top. Check Solution
我做了什么?
public static void main(String[] args)
{
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(1);
int length = list.size();
int firstIndex = list.indexOf(1) + 1;
int secondIndex = firstIndex + list.subList(firstIndex, length).indexOf(1) + 1;
System.out.println(firstIndex);
System.out.println(secondIndex);
}
最佳答案
“所有数字都相等的列表” --> {n,n,...,n,n}。
“我必须返回总和等于目标数的前两个数字的索引”让我们假设 target=x。 因为你的列表充满了相等的数字,如果 x/2=n 你的索引将是 0 和 1,如果 x/2 !=n 你将没有任何匹配
问题版之后
int length=10;
int target=100;
int[] tab1= new int[length];
Object[] tab2= new Object[length];
Object[] tab2Sorted= new Object[length];
for (int i = 0; i < tab2Sorted.length; i++) {
for (int j = i; j < tab2Sorted.length; j++) {
if(tab2Sorted[i]+tab2Sorted[j]==target){
//do what you want on objects to get back indexes
}
}
//As tab3 is sorted you dont have to read all the array
if(tab2Sorted[i]>target/2){
break;
}
}
您只需将 tab2 和 tab2Sorted 类型从 Object 更改为自定义类型,保存第一个选项卡中的 int 及其索引
关于java - 数组列表 : Find nth occurrence of an Integer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32461150/