leetcode1 two sum

https://leetcode.com/problems/two-sum/

1 C++

遍历两次,时间复杂度O(n^2),空间复杂度O(1)

class Solution {
public:
    vector twoSum(vector& nums, int target) {
        
        vector ret;
        for (int i =0;i < nums.size(); i++) {
            for (int j=i+1;j< nums.size(); j++) {
                if(nums[i]+nums[j]==target) {
                    ret.push_back(i);
                    ret.push_back(j);
                }
            }
        }
        return ret;
    }
};

2 java

用字典存value的index,然后遍历,一边遍历,一边找满足条件的点,因为一次遍历时,把index都存起来了,找后面的,都会把前面的比较一次,所以也会把所有的情况都弄完,所以可以通过一次遍历做到。

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

你可能感兴趣的:(leetcode2019)