兩數之和

題目描述:

給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和爲目標值的那 兩個 整數,並返回他們的數組下標。

/*
方法一:暴力搜索法:時間複雜度O(n2)

class Solution {
    public int[] twoSum(int[] nums, int target) {
        if(nums == null || nums.length<1) return null;
        for(int i=0; i<nums.length;i++){
            for(int j= nums.length-1;j>i;j--){
                if(nums[j]+nums[i]== target){
                    return new int[]{i,j};
                    
                }
            }
        }
        return null;
    }
}
*/
/*
方法二:
哈希:時間複雜度O(1)
class Solution{
    public int[] twoSum(int[] nums, int target){
        if(nums == null || nums.length < 1) return null;

        HashMap<Integer,Integer> map=new HashMap<>();
        for(int i=0; i<nums.length;i++ ){
            if(map.containsKey(target-nums[i])){
                return new int[]{map.get(target-nums[i]),i};
            }

            map.put(nums[i],i);
        }

        return null;
    }
}
*/


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章