1. 两数之和

  1. public int[] twoSum(int[] nums, int target) {
  2. int n = nums.length;
  3. for (int i = 0; i < n; ++i) {
  4. for (int j = i + 1; j < n; ++j) {
  5. if (nums[i] + nums[j] == target) {
  6. return new int[]{i, j};
  7. }
  8. }
  9. }
  10. return new int[0];
  11. }
  12. public int[] twoSum2(int[] nums, int target) {
  13. Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
  14. for (int i = 0; i < nums.length; ++i) {
  15. if (hashtable.containsKey(target - nums[i])) {
  16. return new int[]{hashtable.get(target - nums[i]), i};
  17. }
  18. hashtable.put(nums[i], i);
  19. }
  20. return new int[0];
  21. }
  22. //链接:https://leetcode-cn.com/problems/two-sum/solution/liang-shu-zhi-he-by-leetcode-solution/
  23. }