LeetCode第一题

来源:互联网 发布:mac 用apple id登陆 编辑:程序博客网 时间:2024/06/06 03:08

第一天开始,感觉基础还是很差。看了几种方法,最后就贴两种吧。

第一种最笨的方法,时间复杂度O(n~2)

public static int[] twoSum(int[] nums, int target) {int [] answer = new int[2];A:for(int i = 0;i < nums.length;i++){answer[0] = i;for(int j = i + 1;j < nums.length; j++){if(nums[j] == target - nums[i]){answer[1] = j;break A;}}}System.out.println(Arrays.toString(answer));return answer;  }

第二种采用哈希表,就是用Map增加了查询速度

public static int[] twoSum(int[] nums, int target) {Map<Integer, Integer> map = new HashMap<Integer, Integer>();int [] answer = new int[2];for(int i = 0;i < nums.length;i++){map.put(nums[i], i);}for(int i = 0;i < nums.length;i++){int divide = target - nums[i];if(map.containsKey(divide) && map.get(divide)!=i){answer[1] = i;answer[0] = map.get(divide);}}System.out.println(Arrays.toString(answer));return answer;            }
继续努力努力吧。。。

原创粉丝点击