zoukankan      html  css  js  c++  java
  • 1、LeetCode--Two Sum

    question: 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.

    Example:

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

    题目的大概意思是:给你一个包含整型数据的数组,返回两个数组中两个数字的序号,使得他们的值相加等于一个给定的target,我们假设每个输入都会得到一个正确答案
             
    第一种方法(最容易想到的):
    C语言描述,LeetCode代码如下:

    /**
    * Note: The returned array must be malloced, assume caller calls free().
    */
    int* twoSum(int* nums, int numsSize, int target) {
      int *p = (int *)malloc(2 * sizeof(int)); // 注意:分配空间,如果用数组返回会出错
    
      int i, j;
      for(i = 0; i < numsSize - 1; i++)
      {
        int num = target - nums[i];
        for(j = i+1; j < numsSize; j++)
          if(num == nums[j])
          {
            p[0] = i;
            p[1] = j;
            return p;
          }
      }
      return p;
    }

    分析程序:对于数据量很大的整型数组,时间复杂度O(n^2), 空间复杂度O(1)


    第二种方法:
    C++描述, LeetCode代码如下:
    class Solution {
      public:vector<int> twoSum(vector<int>& nums, int target)
        {
         vector<int> vec;
        map<int, int> m;
        for(int i = 0; i < nums.size(); i++)     // 用map来做
          m[nums.at(i)] = i;
        for(int i = 0; i < nums.size(); i++)
        {
          int flag = target - nums.at(i);
          if(m.find(flag) != m.end() && m[flag] != i)   // 判断flag是否在m中, 而且不是当前值 
          {
            vec.push_back(i);
            vec.push_back(m[flag]);
            return vec;
          }
        }
        return vec;
      }
    };

    分析程序:对于数据量很大的整型数组,采用这种方法更好,时间复杂度O(n), 空间复杂度O(n)

    第三种方法:

    class Solution {
      public:
      vector<int> twoSum(vector<int>& nums, int target)
      {
        vector<int> vec;
        map<int, int> m;
        int num, flag;
        for(int i = 0; i < nums.size(); i++)
        {
          num = nums.at(i);
          if(m.find(num) == m.end())               // 不在m中,加入
            m[num] = i;
          flag = target - num;
          if(m.find(flag) != m.end() && m[flag] != i)   // 符合
          {
            vec.push_back(i);
            vec.push_back(m[flag]);
            return vec;
          }
        }
        return vec;
       }
    };

    分析程序:对于数据量很大的整型数组,采用这种方法更好,时间复杂度O(n), 空间复杂度O(n)

  • 相关阅读:
    Java 8 Lambda 表达式
    OSGi 系列(十二)之 Http Service
    OSGi 系列(十三)之 Configuration Admin Service
    OSGi 系列(十四)之 Event Admin Service
    OSGi 系列(十六)之 JDBC Service
    OSGi 系列(十)之 Blueprint
    OSGi 系列(七)之服务的监听、跟踪、声明等
    OSGi 系列(六)之服务的使用
    OSGi 系列(三)之 bundle 事件监听
    OSGi 系列(三)之 bundle 详解
  • 原文地址:https://www.cnblogs.com/wkx12/p/5455552.html
Copyright © 2011-2022 走看看