blog's People
blog's Issues
leetcode题解——Two Sum
题目
我们要对给定的数组进行遍历,在遍历的过程中需要记录之前已经出现过的数字。采用什么数据结构来记录呢?数组的查询效率太低,Set的查询效率虽是O(1),但题目要求返回的是元素的索引,set只能记录一个值,也不符合。查询是O(1),可以记录类似[值-索引]的记录的数据结构那么肯定是Map了。数据结构确定下来,代码就很简单了。
public class Solution {
public int[] twoSum(int[] numbers, int target) {
Map<Integer,Integer> tmp = new HashMap<Integer,Integer>();
int[] result = new int[2];
int remain = 0;
for(int i=0; i<numbers.length; i++){
remain = target - numbers[i];
if(tmp.containsKey(remain)){
result[0] = tmp.get(remain);
result[1] = i;
break;
}else{
tmp.put(numbers[i], i);
}
}
return result;
}
}
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.