LeetCode 1.Two Sum
来源:互联网 发布:楤木淘宝 编辑:程序博客网 时间:2024/06/16 12:59
1.39 ms 暴力
public class Solution { public int[] twoSum(int[] nums, int target) { int first = 0; int second = 0; for (first = 0; first < nums.length; first++) { for (second = first + 1; second < nums.length; second++) { if (nums[first] + nums[second] == target) { return new int[] { first, second }; } } } return new int[] { first, second }; } }
2.62 ms 暴力
public class Solution { public int[] twoSum(int[] nums, int target) { int second = 0; List<Integer> visited = new ArrayList<Integer>(); for (; second < nums.length; second++){ int num = target - nums[second]; if (visited.contains(num)){ return new int[]{visited.indexOf(num), second}; }else{ visited.add(target - num); } } return null; } }
3.12ms 排序+二分查找
public class Solution { private int findBybsearch(int start, int num, List<NumCell> numCells) { int l = start; int r = numCells.size(); while (l < r) { int m = (l + r) >> 1; NumCell numCell = numCells.get(m); if (num > numCell.value) { l = m + 1; } if (num == numCell.value) { return numCell.index; } if (num < numCell.value){ r = m; } } return -1; } private class NumCell implements Comparable<NumCell> { public NumCell(int v, int i) { this.value = v; this.index = i; } public int value; public int index; @Override public int compareTo(NumCell o) { return this.value - o.value; } } public int[] twoSum(int[] nums, int target) { List<NumCell> numCells = new ArrayList<NumCell>(); for (int i = 0; i < nums.length; i++) { numCells.add(new NumCell(nums[i], i)); } Collections.sort(numCells); for (int i = 0; i < numCells.size(); i++) { int num = target - numCells.get(i).value; int index0 = numCells.get(i).index; int index1 = findBybsearch(i, num, numCells); if (-1 != index1) { return new int[] { Math.min(index0, index1), Math.max(index0, index1) }; } } return null; } }
4.8ms Java的Map
public class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> NumMap = new HashMap<>(); for (int i = 0; i < nums.length; i++) { if (NumMap.containsKey(target - nums[i])) { return new int[] { NumMap.get(target - nums[i]), i }; } else { NumMap.put(nums[i], i); } } return null; } }
0 0
- LeetCode 1. Two Sum
- [LeetCode]1.Two Sum
- LeetCode 1.Two Sum
- LeetCode --- 1. Two Sum
- [Leetcode] 1. Two Sum
- leetcode---1.Two sum
- [Leetcode] 1. Two Sum
- LeetCode 1.Two Sum
- LeetCode 1.Two Sum
- LeetCode 1.Two Sum
- 【LeetCode]1.Two Sum
- LeetCode 1.Two Sum
- leetcode 1. Two Sum
- [leetcode] 1. Two Sum
- leetcode 1. Two Sum
- Leetcode- 1. Two Sum
- LeetCode-1.Two Sum
- Leetcode 1. Two Sum
- 第3.1节:访问控制与继承(C++)
- c++整数类型
- 第一章 设计模式入门(策略模式)
- ... operator in ES6
- Spring框架之基于Restful风格实现的SpringMVC
- LeetCode 1.Two Sum
- B/S和C/S的区别
- MySQL数据库优化的八种方式(经典必看)
- 2016年12月21日--心情记录
- qss范例
- B001-云数据中心构建实战
- 源码编译LAMP
- linux下USB设备编号固定
- CSS样式表初始化代码