美文网首页
每日一道leetcode-TowSum

每日一道leetcode-TowSum

作者: Kino_7abb | 来源:发表于2019-01-07 22:23 被阅读0次

    1.每日一道leetcode-TowSum

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

    1.暴力解法,每次循环数组内所有元素x次,然后再循环target - x次
     public static int[] twoSum(int[] nums,int target){
            //循环两次 复杂度为O(n2)--暴力解法
            int length = nums.length;
            int index1 =0;
            int index2 =0;
            for(int i = 0; i < length; i ++){
                for(int j = i+1 ; j < length ; j++){
                    if(nums[i] + nums[j] == target){
                        index1 = i ;
                        index2 = j ;
                    }
                }
    
            }
            int[] res = {index1,index2};
    
            return res;
        }
    

    时间复杂度:O(n^2), 对于每个元素,我们试图通过遍历数组的剩余部分来寻找它所对应的目标元素,这将耗费 O(n)的时间。因此时间复杂度为 O(n^2)

    2.两遍哈希表
      //hash
        public static int[] twoSum2(int[] nums,int target){
            Map<Integer,Integer> map = new HashMap<>();
            for(int i = 0 ; i < nums.length; i ++){
                map.put(nums[i],i);
            }
            for(int i = 0 ; i < nums.length; i ++){
                int res = target - nums[i];
                //map.containsKey(key)-->key(数组中的值),map.get(key)-->value(索引)
                if(map.containsKey(res) && map.get(res) != i){
                    //如果map中有这个值并且索引不是原来的
                    return new int[]{i,map.get(res)};
                }
            }
            throw new IllegalArgumentException("No two sum solution");
        }
    

    时间复杂度为o(n)因为只遍历了一边hash表

    相关文章

      网友评论

          本文标题:每日一道leetcode-TowSum

          本文链接:https://www.haomeiwen.com/subject/kmaprqtx.html