leetcode1. Two Sum
来源:互联网 发布:电动汽车行业前景知乎 编辑:程序博客网 时间:2024/06/18 07:54
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].
解法一
暴力
class Solution { /** * @time O(n^2) * @space O(1) */ public int[] twoSum(int[] nums, int target) { if (nums == null || nums.length == 0) { return null; } for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { return new int[] {i, j}; } } } return null; }}
解法二
hashtable
public class Solution { /* * @time O(n) * @space O(n) */ public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> hashMap = new HashMap<>(); for (int i = 0; i < nums.length; i++) { if (hashMap.containsKey(nums[i])) { int[] result = {hashMap.get(nums[i]), i}; return result; } hashMap.put(target - nums[i], i); } int[] result = {}; return result; }}
阅读全文
1 0
- [LeetCode1] Two Sum
- LeetCode1 Two Sum
- Leetcode1:Two Sum
- leetcode1 two sum
- LeetCode1 Two Sum
- LeetCode1:Two Sum
- leetcode1 Two Sum题解
- leetcode1 Two Sum
- LeetCode1 Two Sum
- LeetCode1:Two Sum
- leetCode1: Two Sum
- leetcode1--Two Sum
- leetcode1 Two Sum
- LeetCode1. Two Sum
- Leetcode1:Two Sum
- leetcode1.Two Sum
- leetcode1 Two Sum
- LeetCode1-Two Sum
- 燃气灶电子点火器原理与检修(图)
- jqery和js如何判断checkbox是否选中
- go chan使用 匿名函数执行
- 【C语言】【unix c】信号的产生
- CTF入门--请输入密码
- leetcode1. Two Sum
- kafka_2.11-0.8.2.1+java 生产消费程序demo示例
- 【九度OJ】1013:开门人和关门人
- 模仿优酷菜单
- 关于#pragma pack(n)引发的一系列问题
- Spark2.x学习笔记:4、Spark程序架构与运行模式
- stm32F1RTC
- python re
- html5-localstorage操作(小demo)