【LeetCode算法题】 Tow Sum

1、给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

第一种是暴力的解法

这道题的题目要求是数组内任意两个元素之和等于给定的目标整数,很容易就想到数组for循环遍历,并且是两层for,所以:

  public static int[] Sum(int [] nums,int target){
        int[] result =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){
                    result [0] = i;
                    result [1] = j;
                    System.out.println("相等:"+i+"   "+j);
                }
            }

        }
        return result;
    }

inputArray是没有被排序的,,就是把nums[0]的数2与其他的数进行加法:
2-----------> 2+(7)==target(9) 数组中有,则返回2和7的索引值
如果没有,则继续查找,知道全部查完为止。
这样的算法时间复杂度为O(n^2)空间复杂度为O(1)

第二种解法使用Map集合

是用空间换时间的做法,时间复杂度O(n)和空间复杂度O(n)
Map(num—>index)
map
1,+8 = 9 1—>0
2, 7 2—>1
9, 0 9—>2
7, 2 (3,1)

public static int [] twoSum(int[] nums,int target){
        int[] res = new int[2];
        if(nums == null||nums.length<=1){
            return res;
        }
        HashMap<Integer,Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int num = nums[i];
            int val = target - num;
            if(map.containsKey(val)){
                res[0] = i;
                res[1] = map.get(val);
                System.out.println(res[0]+"   "+res[1]);
            }else {
                map.put(num,i);
            }
        }
        return res;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章