leetcode-ye

导航

LeetCode No.1 两数之和

1. 暴力法遍历数组

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] ans = new int[2]; 
        for (int i = 0; i < nums.length; i ++) {
            for (int j = i + 1; j < nums.length; j ++) {
                if (nums[i] + nums[j] == target) {
                    ans[0] = i;
                    ans[1] = j; 
                    return ans; 
                }
            }
        }

        return ans; 
    }
}

2. HashMap,key存储数组元素,value存储元素位置

class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        int[] ans = new int[2]; 
        for (int i = 0; i < nums.length; i ++) {
            if (map.containsKey(target - nums[i])) {
                ans[0] = map.get(target - nums[i]);
                ans[1] = i; 
                return ans; 
            }
            map.put(nums[i], i); 
        }

        return ans; 
    }
}

 

posted on 2022-06-11 15:27  XunweiYe  阅读(14)  评论(0编辑  收藏  举报