leetcode第1题(array)

题目:

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

思路分析:

自然最简单的方法就是写两个嵌套循环,但是这样做效率太低,leetcode OJ并没有通过这种方法。既然时间效率太低,那我们就用空间换时间呗。

第一个思路是先排序,再做两个游标,从两头分别向中间递进。由于排序会导致原来的index改变,因此应在排序前为原数组建立一个副本。但是仔细想想这个方法虽然效率有所提高,但是仍然不是最好。

第二个思路是,为了提高查找的速度,我们可以利用hash表的方法,建立一个hash 表,数组里的数为key,其相应的index为value(注意,题目要求index从1开始)。代码如下:

 1 vector<int> twoSum(vector<int>& nums, int target) {
 2        vector<int> result;
 3        unordered_map<int, int> nummap;
 4        for (int i = 0; i<nums.size(); i++)
 5        {
 6             nummap[nums[i]] = i + 1;
 7        }
 8        for (int i = 0; i<nums.size(); i++)
 9        {
10             if (nummap.count(target-nums[i])&&nummap[target-nums[i]] != i + 1)
11             {
12                  if (i + 1<nummap[target-nums[i]])
13                  {
14                      result.push_back(i + 1);
15                      result.push_back(nummap[target-nums[i]]);
16                      break;
17
18                  }
19                  else
20                  {
21                      result.push_back(nummap[target-nums[i]]);
22                      result.push_back(i+1);
23                      break;
24                  }
25
26             }
27        }
28        return result;
29     }

这里需要注意的是,本方法使用了stl的unordered_map,其具体介绍可自行查询一下。另外,由于要求返回的结果,小的index要在前面插入,因此应判断一下。

最值得注意的是:nummap[target-nums[i]] != i + 1,这一句表示杜绝了返回两个相同的index,如[3,2,4],6的情况下,应返回(2,3)而不是(1,1)

时间: 2024-10-14 12:48:09

leetcode第1题(array)的相关文章

leetcode中第一题twosum问题解答算法的可行性证明

leetcode中第一题twosum问题解答算法的可行性证明 一.引入 关于leetcode中第一题twosum问题,网上已有不少高人做出过解答,并提出了切实可行的算法实现.我在解答该题时参考了博客http://www.zixue7.com/article-9576-1.html的解答.为让读者更直观地阅读和理解本文,先简要摘录以上博客的内容如下: 题目还原 Two Sum Given an array of integers, find two numbers such that they a

LeetCode 第 19 题 (Remove Nth Node From End of List)

LeetCode 第 19 题 (Remove Nth Node From End of List) Given a linked list, remove the nth node from the end of list and return its head. For example, Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the li

LeetCode 第 372 题 (Super Pow)

LeetCode 第 372 题 (Super Pow) Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array. Example1: a = 2 b = [3] Result: 8 Example2: a = 2 b = [1,0] Result: 1024 这道题与

【LeetCode每天一题】3Sum(三数之和)

Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not contain duplicate triplets. Example: Given array nums =

LeetCode --- 88. Merge Sorted Array

题目链接:Merge Sorted Array Given two sorted integer arrays A and B, merge B into A as one sorted array. Note: You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements init

LeetCode OJ - Convert Sorted Array/List to Binary Search Tree

虚函数使用的时机 为什么虚函数不总是适用? 1. 虚函数有事会带来很大的消耗: 2. 虚函数不总是提供所需的行为: 3. 当我们不考虑继承当前类时,不必使用虚函数. 必须使用虚函数的情况: 1. 当你想删除一个表面上指向基类对象,实际却是指向派生类对象的指针,就需要虚析构函数. LeetCode OJ - Convert Sorted Array/List to Binary Search Tree,布布扣,bubuko.com LeetCode OJ - Convert Sorted Arra

LeetCode 第 73 题 (Set Matrix Zeroes)

LeetCode 第 73 题 (Set Matrix Zeroes) Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. Follow up: Did you use extra space? A straight forward solution using O(mn) space is probably a bad idea. A simple impro

Leetcode第五题_Longest Palindromic Substring

Longest Palindromic Substring Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring. Leetcode第5题,题目大概意思是给一个字符串,从中找出最长的回文串,所谓回文串,就是

LeetCode 第三题,Longest Substring Without Repeating Characters

题目: Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest s

leetcode第9题-Palindrom Number

这是leetcode的第九题,相对来说比较简单,目的很简单,就是判断一个int型的数是不是回文数.但是有几点需要考虑: 负数应该没有回文数,要加判断!要注意额外的空间申请问题.判断是否是回文数势必要对一个数进行反转,反转的时候就要考虑溢出的问题.实现的代码如下: #include<stdio.h> bool isPalindrom(int x) { if(x<0) return false; else { int tmp=x; int sum=0; while(tmp) { sum=su