zoukankan      html  css  js  c++  java
  • 0001 两数之和

    题目


    给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个整数,并返回他们的数组下标。

    你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

    示例:

    给定 nums = [2, 7, 11, 15], target = 9

    因为 nums[0] + nums[1] = 2 + 7 = 9
    所以返回 [0, 1]

    解法


    我的答案----暴力求解

    遍历两次,代码如下

     1 // kurrrr
     2 class Solution {
     3 public:
     4     vector<int> twoSum(vector<int>& nums, int target) {
     5         vector<int> answer;
     6         for(int i=0; i<nums.size(); i++){
     7             for(int j=i+1; j<nums.size(); j++){
     8                 if(j==i)  continue;
     9                 if((target-nums[i]) == nums[j]){
    10                     answer.push_back(i);
    11                     answer.push_back(j);
    12                     break;
    13                 }
    14             }  
    15         }
    16         return answer;
    17     }
    18 };
    19 
    20 
    21 
    22 // leetcode
    23 class Solution {
    24     public int[] twoSum(int[] nums, int target) {
    25         for (int i = 0; i < nums.length; i++) {
    26             for (int j = i + 1; j < nums.length; j++) {
    27                 if (nums[j] == target - nums[i]) {
    28                     return new int[] { i, j };
    29                 }
    30             }
    31         }
    32         throw new IllegalArgumentException("No two sum solution");
    33     }
    34 }

     建议解法----哈希表

    哈希表:可以根据 key 值访问数据。

    在这里,可以将数组值与其索引关联成哈希表,这样去寻找某特定值得时候就不用遍历数组,从而节省了时间复杂度。

     1 class Solution {
     2     public int[] twoSum(int[] nums, int target) {
     3         Map<Integer, Integer> map = new HashMap<>();
     4         for (int i = 0; i < nums.length; i++) {
     5             map.put(nums[i], i);
     6         }
     7         for (int i = 0; i < nums.length; i++) {
     8             int complement = target - nums[i];
     9             if (map.containsKey(complement) && map.get(complement) != i) {
    10                 return new int[] { i, map.get(complement) };
    11             }
    12         }
    13         throw new IllegalArgumentException("No two sum solution");
    14     }
    15 }
    16 
    17 
    18 作者:LeetCode
    19 链接:https://leetcode-cn.com/problems/two-sum/solution/liang-shu-zhi-he-by-leetcode-2/
    20 来源:力扣(LeetCode)
    21 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
    View Code

    说明


    复杂度

    时间复杂度:执行一段代码所消耗的时间,即代码执行了多少行。通常用大O表示,常用的时间复杂度有O(1),O(logn),O(n),O(n2).

    空间复杂度执行一段代码所消耗的内存。通常用大O表示,常用的空间复杂度有O(1),O(n),O(n2).

  • 相关阅读:
    兼容性问题--HTML+CSS
    限时购--倒计时⏳
    如何把项目上传到GitHub上
    转载:java面试题(一)
    转载:php excel 的处理
    转载:Angular的filter总结
    转载:Think in AngularJS:对比jQuery和AngularJS的不同思维模式(大漠穷秋)
    转载:对比Angular/jQueryUI/Extjs:没有一个框架是万能的
    在eclipse中添加svn插件
    最近的一些事儿
  • 原文地址:https://www.cnblogs.com/kurrrr/p/13130946.html
Copyright © 2011-2022 走看看