看见题目时我直接想到了两层for循环,实现方法如下:
public int[] twoSum(int[] numbers, int target) {
int indexs[]=new int[2];
for(int i=0;i
这个方法的时间复杂度为O(n*n),在我的电脑上运行是成功的,但是在leetcode中提交时出现了超时错误,因为leetcode中的测试数组非常大,这个时间复杂度满足不了。因此学习了别人的代码,改为用hashmap来实现这个算法,因为hashmap查找的时间复杂度为O(1),因此提高了时间复杂度。
public class TwoSumApp {
public static void main(String[] args) {
TwoSumApp s=new TwoSumApp();
int numbers[]={2,7,4,8};
int target=9;
int indexs[]=s.twoSum(numbers, target);
for(int i=0;i
map=new HashMap
();
for(int i=0;i