博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【Tour of LeetCode】Q1——Two Sum
阅读量:5924 次
发布时间:2019-06-19

本文共 2005 字,大约阅读时间需要 6 分钟。

Question

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].

Solution 1 : Brute Force

■ 1st Submission

class Solution {    public int[] twoSum(int[] nums, int target) {        for (int i = 0; i < nums.length; i++) {            for (int j = 0; j < nums.length && j != i; j++) {    // [1]                if (nums[i] + nums[j] == target) {                    return new int[]{i, j};                }            }        }        throw new IllegalArgumentException("No two sum solution");    }}
Finished
Runtime: 0 ms
Your input
[2,7,11,15] 9
Output
[1,0]
Expected
[0,1]
  • Oops, [1] shows that I am not fully understanding the procedure of the "for" loop

■ 2nd Submission

Brute Force with correct "for" loop

class Solution {    public int[] twoSum(int[] nums, int target) {        for (int i = 0; i < nums.length; i++) {            for (int j = 0; j < nums.length; j++) {    // [2]                if (j == i) continue;                if (nums[i] + nums[j] == target) return new int[]{i, j};            }        }        throw new IllegalArgumentException("No two sum solution");    }}
Status
Accepted
Runtime
75 ms
Memory
27.7 MB
  • [2] makes a "drawback" that causes unnecessary calculation
  • Time Complexity : O(n²), Space Complexity : O(1)

■ 3rd Submission

Time-optimized Brute Force

class Solution {    public int[] twoSum(int[] nums, int target) {        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};            }        }        throw new IllegalArgumentException("No two sum solution");    }}
Status
Accepted
Runtime
35 ms
Memory
27.6 MB
  • Is there any other better algorithm?

Solution 2 : ?

See you later

转载地址:http://ymavx.baihongyu.com/

你可能感兴趣的文章
ThoughtWorks技术雷达专区
查看>>
大厂前端高频面试问题与答案精选
查看>>
.NET Framework 4.8预览
查看>>
Tech UP——EGO北京分会成立啦
查看>>
立下“去O”Flag的AWS,悄悄修炼了哪些内功?
查看>>
腾讯云DevOps技术揭秘:新时代运维重器Tencent Hub最佳实践
查看>>
微软开源PDB
查看>>
小米人员架构调整:组建中国区,王川任总裁
查看>>
Avalonia Beta 1对WPF做了很多改进
查看>>
期待已久的Java 9 今日发布
查看>>
Stefan Tilkov:跳过单体应用,从微服务开始
查看>>
小米:开源不仅要站在巨人的肩膀上,还要为巨人指方向
查看>>
Apache HBase的现状和发展
查看>>
Linus Torvalds: 成功的项目源于99%的汗水与1%的创新
查看>>
InfoQ宣布成立CNUT容器技术俱乐部 欲连接中国容器社区
查看>>
GitHub服务中断24小时11分钟事故分析报告\n
查看>>
在微信小程序中绘制图表(part2)
查看>>
新成立的Scala中心将重点关注教育和Scala社区
查看>>
自从装了windows神器,再也不用羡慕mac了
查看>>
Next.js 7发布,构建速度提升40%
查看>>