LeetCodeOJ_001: Two Sum
来源:互联网 发布:值机软件 编辑:程序博客网 时间:2024/06/16 03:37
本文目录
- 本文目录
- 题目
- AC代码
每天一道LeetCode.
原题目:https://leetcode.com/problems/two-sum
题目
Total Accepted: 512743 Total Submissions: 1544952 Difficulty: Easy Contributor: LeetCode
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].
Subscribe to see which companies asked this question.
AC代码
import java.util.HashMap;public class Solution { public int[] twoSum(int[] nums, int target) { int[] sum = new int[2]; for (int i = 0; i < nums.length; i++) { for (int j = i+1; j < nums.length; j++) { if(target - nums[i] == nums[j]) { sum[0] = i; sum[1] = j; } } } return sum; }}
Time complexity : O(n^2). For each element, we try to find its complement by looping through the rest of array which takes O(n) time. Therefore, the time complexity is O(n^2).
Space complexity : O(1).
这是我的AC代码
public class Solution { public int[] twoSum(int[] nums, int target) { int[] result = new int[2]; for(int i=0; i<nums.length; i++) { //a + b = target int a = nums[i]; int b = target - a; for (int j = 0; j < nums.length; j++) { if ((b == nums[j]) && (i != j)) { result[0] = i < j ? i : j; result[1] = i > j ? i : j; break; } } } return result; }}
- LeetCodeOJ_001: Two Sum
- Two Sum
- Two Sum
- Two Sum
- two sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Netty(一)核心概念
- Python基础 for循环
- 装载、链接与库——main函数的前世今生
- pxe
- keras系列︱图像多分类训练与利用bottleneck features进行微调(三)
- LeetCodeOJ_001: Two Sum
- normalize.css使用方法
- Sql Server服务远程过程调用失败
- 个人学习总结一机器学习入门(十)
- Linux文件编程
- 关键字之操作符(运算符)
- 2017 计蒜之道 初赛 第六场
- smaba
- printf 函数的输出条件