Leet Code OJ 1. Two Sum [Difficulty: Easy]
来源:互联网 发布:淘宝卖家如何退出村淘 编辑:程序博客网 时间:2024/05/16 02:55
题目:
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,返回2个元素的下标,它们满足相加的和为target。
你可以假定每个输入,都会恰好有一个满足条件的返回结果。
C#:
public int[] RetTwonum(int[] num,int target)
{
int[] result = new int[2];
for (int i = 0; i < num.Length; i++)
{
for (int j = i+1; j < num.Length - 1; j++)
{
if (target == num[i] + num[j])
{
//result =new int[] {i,j };
result[0] = i;
result[1] = j;
}
}
}
return result;
}
python :(2种,这块参考了其他的博客)
”’
class Solution(object) :
def twoSum(self,nums,target):
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i]+nums[j]==target:
return i,j
”’
class Solution1(object) :
def twoSum(self,nums,target):
dict = {}
for i in range(len(nums)):
x = nums[i]
if target - x in dict:
return (dict[target - x],i)
dict[x] = i
a=Solution1()
nums = [0,2,4,0]
target = 0
print(a.twoSum(nums,target))
- Leet Code OJ 1. Two Sum [Difficulty: Easy]
- Leet Code OJ 1. Two Sum [Difficulty: Easy]
- Leet Code OJ 1. Two Sum [Difficulty: Easy]
- Leet Code OJ 1. Two Sum [Difficulty: Easy]
- Leet Code OJ 231. Power of Two [Difficulty: Easy]
- Leet Code OJ 21. Merge Two Sorted Lists [Difficulty: Easy]
- Leet Code OJ 112. Path Sum [Difficulty: Easy]
- Leet Code OJ 292. Nim Game [Difficulty: Easy]
- Leet Code OJ 242. Valid Anagram [Difficulty: Easy]
- Leet Code OJ 258. Add Digits [Difficulty: Easy]
- Leet Code OJ 226. Invert Binary Tree [Difficulty: Easy]
- Leet Code OJ 283. Move Zeroes [Difficulty: Easy]
- Leet Code OJ 217. Contains Duplicate [Difficulty: Easy]
- Leet Code OJ 169. Majority Element [Difficulty: Easy]
- Leet Code OJ 263. Ugly Number [Difficulty: Easy]
- Leet Code OJ 100. Same Tree [Difficulty: Easy]
- Leet Code OJ 70. Climbing Stairs [Difficulty: Easy]
- Leet Code OJ 202. Happy Number [Difficulty: Easy]
- poj-2046-循环子串问题
- Linux Socket编程
- Linux下进程间通信概述
- 在着手准备做一个开发项目(web前端),需要做哪些准备?
- 计算机中的定点数和浮点数
- Leet Code OJ 1. Two Sum [Difficulty: Easy]
- MYSQL+vs2010+Navicat基础笔记
- LintCode 解题记录17.8.19 字符串处理6
- (已解决)雷柏v500在Ubuntu系统下键位映射错误
- 【cas】sso和cas概述
- 常见的动态规划问题分析与求解
- 个人随笔和笔记:响应式布局meta声明
- iOS时间戳
- map reduce lambda 区别 用法 结合使用