• leetcode 1 Two Sum


    题目内容

    Given an array of integers, return indices of the two numbers such that they add up to a specific target.

    You may assume that each input would have exactly one solution, and you may not use the same element twice.

    Example:
    Given nums = [2, 7, 11, 15], target = 9,
    
    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].
    

    分析过程

    • 题目归类:
      数组,遍历。
    • 边界分析:
      • 空值分析
        当nums 为null时应该返回null。
      • 循环边界分析
        循环变量不能超过nums.length-1;
    • 方法分析:
      • 数据结构分析
        数据的遍历,tmp = target - 当前值,向后查找是否有和tmp相同的数据。返回下标。
        提前定义一个int[] indice数组用来保存下标。
      • 状态机
      • 状态转移方程
      • 最优解
    • 测试用例构建
      [].
      [1,2,3,4].

    代码实现

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

    效率提高

    采用HashMap每次添加值,key为具体值,value 为 indice。

    import java.util.*;    
    class Solution {
            public int[] twoSum(int[] nums, int target) {
                Map<Integer,Integer> hashTable = new HashMap<>();
                int [] indice = new int[2];
                if(nums == null)
                    return indice;
                for(int i = 0; i<nums.length;i++){
                    int tmp = target - nums[i];
                    if(hashTable.containsKey(tmp)){
                        indice[0] = i;
                        indice[1] = hashTable.get(tmp);
                        break;
                    }else{
                        hashTable.put(nums[i],i);
                    }
                }
                return indice;
            }
        }
    


    可以看到时间复杂度提高了40倍。

    拓展问题

    • 出现多种情况满足相加和等于target,且可以用自己自身两次,求所有的indice 保存到List 中。
    • 3Sum
    • 4Sum
    • Two Sum II - Input array is sorted
    • Two Sum III - Data structure design
    • Subarray Sum Equals K
    • Two Sum IV - Input is a BST
    • Two Sum Less Than K
  • 相关阅读:
    电脑无损换硬盘,不用重装系统驱动的小技巧
    OSPF协议原理及配置5-LSA分析
    OSPF协议原理及配置3-邻居关系的建立
    OSPF协议原理及配置2-理解邻居和邻接关系
    我在华为写代码
    嵌入式未来发展
    blog to live,do not love to blog
    浮点数转换为新类型时必须做范围检查
    分享点干货
    基础C语言知识串串香14☞增补知识
  • 原文地址:https://www.cnblogs.com/clnsx/p/12236574.html
Copyright © 2020-2023  润新知