【发布时间】:2015-12-04 08:04:33
【问题描述】:
在 ArrayList 中查找第 n 次出现的数字的最佳方法是什么?
我已经知道了什么?
- 查找lastIndexOf号码的List接口有方法,在ArrayList类中实现。
- 要查找第一次出现,请使用 indexOf 方法。
我在解决什么问题?
在一个问题中,有一个包含不同数字的列表,我必须返回两个数字的索引,其总和等于目标数字。
例如:List = (1,2,1) & target = 2;
现在1 + 1 =2 和答案将是第一个 1 和第二个 1 的索引。
注意:我已经解决了这个问题,我需要回答这个问题 顶端。 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);
}
【问题讨论】:
-
假设您最好的意思是高效,您希望从 O(n^2) 的时间复杂度降低到较低的时间复杂度。检查我的 O(n*logn) 答案
-
您的解决方案不是最有效的。请参阅My Solution,它实现了@DiegoMartinola 的想法。老实说,我并没有窃取 Diego 的想法,而是我独立提出的。