豆瓣日记上的英语经

如何迅速提高英语阅读能力?

  • 对于中初级学习者来说,迅速提高词汇量比分辨近义词的差别更重要。
  • 只要你不是从小大量阅读英文,背单词就是必须的。
  • 要按照读音来记单词
  • 阅读的时候脑子要思考,不断地问:作者在说什么?文章的走向是怎么样的?里面有哪一些核心内容?有什么样的情感?带着目的去阅读,而非无意识阅读。无意识阅读法,只能浪费时间。
  • 在读复杂句的时候,或者碰到不明白的句子的时候,脑子要分清楚主语、谓语、宾语之间的修饰关系。比如说这个It指代了谁?这句超级无敌长的复杂句里,主谓宾在哪里?修饰是放在前面还是后面了?读的时候可以不做语法分析,但是一定要弄明白每个单词在句子里所扮演的角色,以及它们之间所产生的关系。长难句是绝对绕不过去的一个坎,不要心存侥幸,现在就赶紧解决它吧。
  • 千万不要总是跳过不懂的东西。

中国人说英语为什么听起来没有礼貌?(8.17更新添加中英文化差异的讨论)

  • 中国人的英语以 Chinglish 或 Chenglish 闻名于世。中国人最大的英语发音问题就是没有连读,但这都不是最主要的语言问题。老外们时常议论,很多中国人在说英语时,听起来没有礼貌;并不是这些中国人本身没礼貌,而是他们还没有习惯英语的礼貌表达方式
  • 比如,中国人在餐厅或咖啡厅,会说:“我想要一个汉堡包”或者“我想要一杯咖啡”。但是,如果直接把这些话翻译成英语“I want to have a hamburger.”或“I want to have a coffee.”老外们会觉得这样说话很没有礼貌,当然他们也不会直接告诉你。而在西方国家,老外们一般会说:“Could I have a hamburger, please?”或“Can I have a coffee, please?”在这里joy同学又提到一个需要注意的问题,“打工的孩子最容易不注意的是see you. See u应该是客人说的,隐含了他觉得不错他会再来的意思,而店员最好用低调一点的bye,用see u太强势了。另外人家说谢谢,你也不用说you are welcome, 这实在是太正式了,有点真把自己当回事觉得帮了人家的味道。回答 cheersno worries 就好,如果仅仅是对方爱说谢,你甚至可以不回应他的谢,直接说你要说的就好,如果是买了他的东西他谢你,更不能说you r welcome了
  • 再比如,中国人在拒绝别人邀请的午宴或晚宴时,会说:“抱歉,我不能去,我还有别的安排。”翻译成英文就是“Sorry,I can’t. I have another appointment.”如果这样说,那别人第二次也许不会再邀请你了。老外们一般会这样说:“**That is a good idea! I would like to join in but I have another appointment today.**”

LeetCode - Algorithms - 146. LRU Cache

这题是 Top Interview QuestionsTop 100 Liked Questions之一,前后又花了一个星期。

先是了解了下 Cache replacement policies,其中提及 General implementations of Least recently used (LRU) require keeping “age bits” for cache-lines and track the “Least Recently Used” cache-line based on age-bits.

题目里提示 Could you do both operations in O(1) time complexity? ,又了解了下Time complexity。又在kindle上翻了下《算法图解》,了解了下散列表、链表等数据结构,也算加强了下对哈希表的认识。

在平均情况下, 散列表执行各种操作的时间都为O(1)。 O(1)被称为常量时间。你以前没有见过 常量时间,它并不意味着马上,而是说不管散列表多大,所需的时间都相同。

实际上,你以前见过常量时间——从数组中获取一个元素所需的时间就是固定的:不管数组多大,从中获取一个元素所需的时间都是相同的。

填装因子(load factor)度量的是散列表中有多少位置是空的。填装因子越低,发生冲突的可能性越小,散列表的性能越高。一个不错的经验规则是:一旦填装因子大于0.7,就调整散列表的长度。

自己琢磨也是徒劳,不如上网找点提示信息,在quora上找到几条信息

Typically LRU cache is implemented using a doubly linked list and a hash map.

An LRU Cache should support fast lookup. Apparently, in order to achieve fast lookup, we need to use Hashtable or HashMap.Also, an LRU Cache requires that insert and delete operations should be in O(1) time. The obvious choice for this requirement is Linked List. Linked List support insert/delete operations in O(1) time if we have the reference of element. While building an LRU cache requires that you think in terms of these two data structures. The reality is that these two data structures actually work coherently to achieve the design.So, we are finalizing on these data structures: HashMap and Doubly Linked List. HashMap holds the keys and values as reference of the nodes (entries) of Doubly Linked List.Doubly Linked List is used to store list of nodes (entries) with most recently used node at the head of the list. So, as more nodes are added to the list, least recently used nodes are moved to the end of the list with node at tail being the least recently used in the list.

自己对java集合类库还是不够熟悉,看到Is there any doubly linked list implementation in Java?才明白原来java.util.LinkedList本来就可以当双向链表使用,

Doubly-linked list implementation of the List and Deque interfaces. Implements all optional list operations, and permits all elements (including null).All of the operations perform as could be expected for a doubly-linked list. Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index.

在leetcode上提交了两次,终于运行通过,如果自己来实现双向链表是不是更能提高性能? 做了这些题,感觉leetcode的算法题不是那种难得要死的题,不会做说明你的数据结构和算法知识还比较欠缺。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class LRUCache {
private LinkedList<DualLinkNode> list;
private Map<Integer,DualLinkNode> map;
private final int cacheSize;

public LRUCache(int capacity) {
list = new LinkedList<DualLinkNode>();
map = new HashMap<Integer,DualLinkNode>();
this.cacheSize = capacity;
}

public int get(int key) {
if (map.containsKey(key)) {
DualLinkNode node = map.get(key);
list.remove(node);
list.addFirst(node);
return node.val;
}
else {
return -1;
}
}

public void put(int key, int value) {
if (map.containsKey(key)) {
DualLinkNode node = map.get(key);
list.remove(node);
node.val=value;
list.addFirst(node);
}
else {
if (list.size()==cacheSize) {
DualLinkNode node = list.pollLast();
map.remove(node.key);
}
DualLinkNode node = new DualLinkNode(key,value);
list.addFirst(node);
map.put(key, node);
}
}

private class DualLinkNode {
public int key;
public int val;

public DualLinkNode(int key, int val) {
super();
this.key = key;
this.val = val;
}
}
}

Submission Detail

  • 18 / 18 test cases passed.
  • Your runtime beats 7.69 % of java submissions.

AWS Certified Solutions Architect

How did you prepare for AWS Certified Solutions Architect - Associate Level certification?
https://www.quora.com/How-did-you-prepare-for-AWS-Certified-Solutions-Architect-Associate-Level-certification

Preparing for the AWS Certified Solutions Architect Associate Certification Exam
https://blog.newrelic.com/2018/05/30/aws-certified-solutions-architect-associate-exam-prep/


AWS Certified Solutions Architect - Associate
https://aws.amazon.com/certification/certified-solutions-architect-associate/

AWS Certified Solutions Architect – Associate
https://aws.amazon.com/tw/certification/certified-solutions-architect-associate/

AWS Certified Solutions Architect – Associate
https://aws.amazon.com/cn/certification/certified-solutions-architect-associate/

AWS Well-Architected
采用架构最佳实践进行学习、测量和构建
https://aws.amazon.com/cn/architecture/well-architected/

AWS Well-Architected
Learn, measure, and build using architectural best practices
https://aws.amazon.com/architecture/well-architected/

https://aws.amazon.com/cn/getting-started


Amazon Web Services - Documentation
Documenting Amazon Web Services and SDKs
https://github.com/awsdocs

LeetCode - Algorithms - 7. Reverse Integer

Java

1

自己做出来的naive solution,直接把整数转换成字符串,然后逆转字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public int reverse(int x) {
int r = 0;
if (x>Integer.MAX_VALUE || x<Integer.MIN_VALUE) {
return r;
}
String s = Integer.toString(x);
if (s!=null && !s.isEmpty()) {
String ss = "";
char c = 0;
if (x<0)
s = s.substring(1);
for(int i=s.length()-1;i>=0;i--) {
c = s.charAt(i);
ss += c;
}
if (x<0)
ss = '-'+ss;
System.out.println("ss="+ss);
try {
r = Integer.parseInt(ss);
} catch (NumberFormatException ex) {
r = 0;
}
}
return r;
}
}

Submission Detail

  • 1032 / 1032 test cases passed.

2

9. Palindrome Number ,提示Coud you solve it without converting the integer to a string? 发现人家的方法更直接利落,温故而知新,重新实现下,结果被卡在 java int out of range 的问题里,1534236469 逆序数超过Integer.MAX_VALUE 返回 1056389759,题目里就提示了 Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. 最后想到不如把逆序数变量定义为 long类型,再判断是否超过2147483647(0x7fffffff, 2^31-1),再把long 安全地转换为int返回,java的long安全转换为int的小问题,google关键字 java long to int 参考了下 Safely casting long to int in Java 这样就ok了,在leetcode上运行通过。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public int reverse(int x) {
if (x>Integer.MAX_VALUE || x<Integer.MIN_VALUE) {
return 0;
}
if (x==0) return 0;
int r = 0;
int remainder = 0;
long reverseNumber = 0L;
for(int t = x>0?x:-x; t>0; t/=10) {
remainder = t%10;
reverseNumber *= 10;
reverseNumber += remainder;
}
if (reverseNumber>Integer.MAX_VALUE)
r = 0;
else
r = Long.valueOf(reverseNumber).intValue();
if (x<0)
r *= -1;
return r;
}
}

Submission Detail

  • 1032 / 1032 test cases passed.
  • Runtime: 21 ms
  • Your runtime beats 97.62 % of java submissions.

LeetCode - Algorithms - 9. Palindrome Number

一个多月前就看了下,这题label为Easy,跟 7. Reverse Integer 有关系,自己做7. Reverse Intege时就简单把整数转为字符串来解决,而这题提示Coud you solve it without converting the integer to a string,自己对c语言为例的过程化编程还是欠差,google 关键字 Palindrome Number,出来

最后参照 C Program to Check Whether a Number is Palindrome or Not 的写了java代码,在Eclipse里跑了下,结果不对,又看人家的代码,看来自己还是不理解这个求逆序数的步骤

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public boolean isPalindrome(int x) {
boolean b = false;
int originalInteger = x;
int reversedInteger = 0, remainder = 0;
int t = x;
while (t>0) {
remainder = t%10;
reversedInteger = reversedInteger*10+remainder;
t /= 10;
}
if (originalInteger==reversedInteger)
b = true;
return b;
}
}

Submission Detail

  • 11508 / 11508 test cases passed.
  • Your runtime beats 58.36 % of java submissions.

LeetCode - Algorithms - 3. Longest Substring Without Repeating Characters

一个多月以前就开始看这个题,先是澄清了下 Substring 与 Subsequence的区别。算法是自己的短板与软肋呀,知之甚少的地方,你再思考也还是只有迷惘,只好上网搜罗,google关键字longest unique substring java搜到:

看了还是不理解,人家的代码实现也看了,也没看明白。

又 google 关键字 longest unique substring in a string,搜到 How To Find Longest Substring Without Repeating Characters In Java?,这个终于看懂了,用到了个LinkedHashMap数据结构来存储无重复字符的substring,从左往右扫描字符数组,一旦字符与HashMap里的字符有重复,就把循环变量i置为那个重复字符在原字符串中的位置,HashMap清空,如果字符不重复,就继续往右扫,如果HashMap的size大于最大无重复子串长度,就更新最大无重复子串长度这个int变量,直到字符串末尾为止。会者不难,难者不会,其实也就这么简单。思路是人家的,自己不过照着人家的解决方案写的,最后写下来代码倒也没几行,LeetCode运行通过了。基本理解了,但要达到了然于胸的程度,还得继续慢慢消化理解。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public int lengthOfLongestSubstring(String s) {
int maxUniqSubstrLen = 0;
if (!s.isEmpty()) {
LinkedHashMap<Character,Integer> map = new LinkedHashMap<Character,Integer>();
int len = s.length();
for(int i=0;i<len;i++) {
char ch = s.charAt(i);
if (!map.containsKey(ch)) {
map.put(ch, i);
}
else {
i = map.get(ch);
map.clear();
}
if (map.size()>maxUniqSubstrLen)
maxUniqSubstrLen = map.size();
}
}
return maxUniqSubstrLen;
}
}

Submission Detail

  • 983 / 983 test cases passed.
  • Your runtime beats 10.69 % of java submissions.

新概念英语

  • 新概念英语的文章非常经典,适合学生背诵,从第二册49课,the end of the dream开始,一直背到第三册结束。
  • 推荐英音版本的(即使你是想学美音),因为那个版本比较抑扬顿挫,比较利于记忆、背诵以及语感的养成。一定要模仿任何一处的语音语调,no matter how wierd or stupid it sounds。
  • 因为《新概念英语》教材的经典,其也不可避免的具有因“陈旧”所导致的种种薄弱之处。和即时的新闻和美剧电影来比,用词和题材有些过时。
  • 一来《新概念英语》本身不具备较为正规的测评系统,没有考试,以至于学生很难全面客观地检验学习效果;二来《新概念英语》的知识比较陈旧,与当代发生的新事,当前热门的话题,当下关注度高的问题稍有脱离。
  • 一定要模仿原声课文,一句一句重复模仿,直到可以把每个句子听得很透,甚至可以背下来;尤其开始不要觉的课文很熟了就脱离原声模仿,有很多同学听熟了就自己大声读,读几遍就又回到原来的口音上了。

Book 3: Developing Skills

  • 新概念三册中大部分的叙事文章,例如第5、6、13、15、16、31、33等课,都是很好的复述素材。
  • 31课人物描写的模板、12和41课对比论证的模板、以及59课兴趣爱好的模板。
  • 31课第一段提炼出来的描述人“先否后肯”模式的模板
  • 59课最后一段列出了“收藏”这项爱好的五重好处,即:休闲娱乐、增长知识、结交好友、周游世界、建立自信。通过分析,我们发现,任何有益的爱好都不外乎这几点好处,也就是说,在描述我们爱好及其优点的时候,就可以把这几点套用上去。
  • 第1课的同位语从句、第6课的独立主格、第29课的主语从句
  • 第3, 5, 6, 7, 17, 39等十几篇课文中都为我们提供了非常漂亮地道的亮点句型
  • 对比逻辑的文章,我们可以结合12、27、29、41这几课对比模板轻松应对
  • 第17课是讲解和练习Skimming (略读) 和Scanning (查读)的经典文章。
  • 而下半册中,第51和55课是典型科技类文章的阅读
  • 第六课有两处非常明显地使用了独立结构
  • 第三课An unknown goddess: 英语思维至高无上的秘诀:英文永远是开门见山的,总是把最重要的中心先说出来。更通俗一点来讲,中文的习惯表达方式是因为所以,而英文的表达习惯一般是之所以是因为。
  • 第9课重点训练“数字”的听辨、第27课综合训练“数字、人名、地名”等细节的听辨能力,并以此为例,系统讲解听力“笔记法”

Book 4: Fluency in English

  • 新概念四中的文章是编者ALEXANDER精心挑选的各个领域的散文名篇,这些文章文笔优美,说理透彻。
  • 高超的“破题”范本。以第五课《青年》(Youth)为例,作者在讨论代沟问题、为年轻人辩护时,开篇就指明了问题的根本所在:Let’s get down to fundamentals and agree that the young are after all human beings—-people just like their elders。作者接着指明两者之间的唯一差别就是:年轻人前程似锦,而老年人一切辉煌都已成过眼云烟。这样,下文的论证就有了坚实的基础。我们在写作时,可以参考这种方法,在开篇把问题的根本所在讲明白,这样下文就有话可说,而且容易让人信服。
  • 第24课《美》(beauty):作为一个极其抽象的概念,“美”究竟是什么本来就很难写清楚,而作者在第一段就给“美”下了巧妙的定义:美总会让人想到超越我们俗世的另外一个世界。在这个框架中讨论“美”,就可以有的放矢了。
  • 数字、比较论证技巧:第2课《不要伤害蜘蛛》(spare that spider)
  • 第19课《话说梦的本质》(The stuff of dreams)、十四课《蝴蝶效应》(The Butterfly Effect) :“以退为进”法 这种技巧适用于驳论。
  • 第31课中的“先抑后扬”法
  • 第28课的“例证——极度例证”法
  • 第5课《青年》(Youth)的修辞:两个future第一个future前用了glorious来修饰,在第二个future前则用splendid。再看下一句话:He may be conceited, ill-mannered, presumptuous, or fatuous, ……。这句话中,作者一连串用的四个形容词恰倒好处,令人叫绝。
  • 第24课中可以学到典型的排比句用法
  • 第31课中作者则巧妙地使用了倒装句式
  • 第23课中的长句很多
  • 第11课《如何安度晚年》(How to grow old)是修辞格使用的经典范例。作者在文中把人生比作河流(An individual human existence should be like a river), small at first指的是人的儿童期,rushing passionately指的是人的青年期,boulders 和waterfalls则喻指人生中的坎坷,而become merged in the sea则是指死亡。某种程度上来说,正是这绝妙的比喻使这段话成为英语散文中的经典语段。
  • Lesson 4,属于伪科学盛行时期的产物
  • 第5课 youth 原文是Fielden Hughes 所写的”out of the air”
  • Lesson6:The sporting spirit,乔治·奥威尔(George Orwell)
  • Lesson14:The Butterfly Effect。 美国科普畅销书作家詹姆斯·格雷克 (James Gleick)

Book 2: Practice & Progress

一至三单元主要训练学生写简单句、并列句和复合句


请各位知友分享下自己的英语学习经验吧? - 尤雨溪的回答 - 知乎
https://www.zhihu.com/question/20118811/answer/14036822

  1. 听说读写无障碍,文学类除外。经常有老美发现我不是native speaker的时候很惊讶。
  2. 当年学的时候就是把新概念第二册起的课文听 -> 读 -> 背 -> 说,如此循环。说这一步最关键,要求是能够理解之后像正常思考一样说出来,就像演讲一样。最好是有懂英语的人听着你说,看你说得自然不自然。做到这一步意味着要把文章的词汇、句式、行文思路全部吸收。
  3. 小学6年级开始学英语。初二开始用2里面的方法,高二背完新概念第四册第二遍。之后基本没有刻意再学过。

英语是否会成为开发工程师的发展瓶颈? - 尤雨溪的回答 - 知乎
https://www.zhihu.com/question/55998388/answer/167024826

不仅英语差会成为瓶颈,英语好还能成为优势,因为学习效率会比别人高。像我这样半路出家自学的人,只能靠英语了…

上了大学还是完全不懂语法只想靠美剧或者英语书籍来的语感强行记忆,这种做法靠谱吗? - 尤雨溪的回答 - 知乎
https://www.zhihu.com/question/22027426/answer/21944576

语法也不是完全不需要。或者说,你需要做到的是借助语法去理解你看不懂的句子,而不是去记忆语法本身。理解的过程就是培养语感的过程。从这个角度来说,一些基础的语法知识,比如时态、从句啥的,是培养语感的前提条件。但是,我的看法是语法过了初学者的坎之后就不再是需要刻意去研究的东西,非英语专业尤其如此。

我自己就是语感党,以前考试从来都靠语感,从来不会去记忆具体的语法规则。至于效果… 我高二托福考了673(当时满分677),上海高考 146/150,还拿了个英语比赛的一等奖,高考可以加20分的那种。高中毕业后直接来美国读本科(参加高考是为了防止签证签不出),读硕士,工作,除了本科时候 Liberal Arts 的恐怖阅读量有点累,其他时候英语上从来没有什么障碍。

但是联系到题主的问题,语感的培养绝对不能只靠被动的接收,必须要靠主动的使用。只看书看剧带来的提高是非常有限的,语感只有在使用中才能提高。所以,除了看和听,还要写和说。写嘛,现在网络这么发达,多逛逛外国网站跟人交流或者辩论都可以,但务必保证发言要言之有物。之所以辩论会很有效是因为你需要很努力地思考组织语言去论证自己的正确性。说的方面,在缺少口语交流环境的情况下,背是一个机械但有效的方法。以我自己来说,实质性提高英语的主要手段是靠背新概念 + 背词汇… (参见我这个答案 http://www.zhihu.com/question/20118811/answer/14036822 )所以说到底还是没有什么捷径可走的,想提高英语总得有所付出。

bash shell

BASH Programming - Introduction HOW-TO

by Mike G mikkey at dynamo.com.ar

http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO.html

Bash scripting cheatsheet
https://devhints.io/bash


Bash scripting for beginning system administrators
A hands-on approach
https://www.ibm.com/developerworks/aix/library/au-getstartedbash/

适合系统管理新手的 bash 脚本编程
动手实践方法
https://www.ibm.com/developerworks/cn/aix/library/au-getstartedbash/index.html


Bash by example, Part 1
Fundamental programming in the Bourne again shell (bash)
https://www.ibm.com/developerworks/library/l-bash/index.html

Bash 实例,第一部分
Bourne again shell (bash) 基本编程
https://www.ibm.com/developerworks/cn/linux/shell/bash/bash-1/


Bash by example, Part 2
More bash programming fundamentals
https://www.ibm.com/developerworks/linux/library/l-bash2/index.html

Bash 实例,第 2 部分
更多的 bash 基本编程
https://www.ibm.com/developerworks/cn/linux/shell/bash/bash-2/


Bash by example, Part 3
Exploring the ebuild system
https://www.ibm.com/developerworks/library/l-bash3/index.html

Bash 实例,第 3 部分
探讨 ebuild 系统
https://www.ibm.com/developerworks/cn/linux/shell/bash/bash-3/


Bash 脚本 set 命令教程
http://www.ruanyifeng.com/blog/2017/11/bash-set.html

Spring Boot+React.js

Bootiful Development with Spring Boot and React
https://developer.okta.com/blog/2017/12/06/bootiful-development-with-spring-boot-and-react

Spring Boot API with React UI
https://github.com/oktadeveloper/spring-boot-react-example


Build a CRUD Application with React, Spring Boot, and User Authentication
https://stormpath.com/blog/crud-application-react-spring-boot-user-authentication

React App with Spring Boot
https://github.com/stormpath/stormpath-spring-boot-react-example


Building Spring Boot, MongoDB and React.js CRUD Web Application
https://www.djamware.com/post/5ab6397c80aca714d19d5b9c/building-spring-boot-mongodb-and-reactjs-crud-web-application

Building Spring Boot, MongoDB and React.js CRUD Web Application
https://github.com/didinj/spring-boot-mongodb-react-java-crud


How to Setup Spring-Boot with ReactJS and Webpack
https://medium.com/@benjaminliu_42474/how-to-setup-spring-boot-with-reactjs-and-webpack-9b190edeb0c8

Spring Boot with ReactJS using WebPack and Yarn.
https://github.com/liuben10/spring-boot-react-js-example

LeetCode解题日志

Algorithms

2. Add Two Numbers

用链表模拟十进制加法运算,linked list有点犯晕,在Eclipse IDE上调试了半天才跑通了,只会瞎用框架和库的人算法方面果然是菜鸟。

一开始出来的结果顺序老是逆着。在网上找了个Function to reverse the linked list,incline到自己那代码里,最后总算在LeetCode上跑过了。

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode node1 = l1, node2 = l2;
ListNode node = null, tmpNode = null;
int sum = 0;
boolean b = false;
while (node1 != null || node2!=null) {
node = new ListNode(0);
sum = (node1!=null?node1.val:0) + (node2!=null?node2.val:0);
if (b) sum++;
node.val = sum<10?sum:sum%10;
b = sum>=10 ? true : false;
if (tmpNode!=null)
node.next = tmpNode;
if (node1!=null)
node1 = node1.next;
if (node2!=null)
node2 = node2.next;
tmpNode = node;
}
if (b) {
ListNode node3 = node;
node = new ListNode(1);
node.next = node3;
}
ListNode prev = null;
ListNode current = node;
ListNode next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
node = prev;
return node;
}

/**
* Definition for singly-linked list.
*/
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}

Submission Detail

  • 1562 / 1562 test cases passed.

写完了过上一段时间,又忘了是怎么做对的,在IDE上debug出来的代码,可能做得比较勉强。

1. Two Sum

Java

Brute Force

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] idxArr = {0,0};
for(int i=0;i<nums.length;i++)
for(int j=nums.length-1;j>i;j--) {
if (nums[j]+nums[i]==target) {
idxArr[0] = i;
idxArr[1] = j;
return idxArr;
}
}

return idxArr;
}
}
Submission Detail
  • 20 / 20 test cases passed.
  • Your runtime beats 30.47 % of java submissions.

Hash Table

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public int[] twoSum(int[] nums, int target) {
int a = 0, b = 0;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
a = i;
b = map.get(complement);
} else {
map.put(nums[i], i);
}
}
return new int[]{a, b};
}
}

Submission Detail

  • 29 / 29 test cases passed.
  • Runtime: 2 ms, faster than 72.04% of Java online submissions for Two Sum.
  • Memory Usage: 39.2 MB, less than 98.23% of Java online submissions for Two Sum.

Database

175. Combine Two Tables

mysql

1
2
3
select p.FirstName FirstName,p.LastName LastName,a.City City, a.State State 
from Person p
left outer join Address a on p.PersonId=a.PersonId

Submission Detail

  • 7 / 7 test cases passed.
  • Your runtime beats 84.70 % of mysql submissions.

Transact-SQL

1
2
3
SELECT P.firstName AS 'firstName', P.lastName AS 'lastName', A.city AS 'city', A.state AS 'state' 
FROM Person AS P
LEFT OUTER JOIN Address AS A ON A.personId = P.personId

Submission Detail

  • 8 / 8 test cases passed.
  • Your runtime beats 44.40 % of mssql submissions.

176. Second Highest Salary

mysql

1

1
2
select IF(count(distinct Salary)>1,min(t.Salary),null) SecondHighestSalary from 
(select Salary from Employee order by Salary desc limit 2) t
Submission Detail
  • 7 / 7 test cases passed.
  • Your runtime beats 90.90 % of mysql submissions.

2

1
2
3
4
select
(
select distinct Salary from Employee order by Salary desc limit 1,1
) AS SecondHighestSalary
Submission Detail
  • 7 / 7 test cases passed.
  • Your runtime beats 88.73 % of mysql submissions.

Transact-SQL

1
2
3
4
5
6
7
8
9
10
11
12
13
SELECT 
CASE
WHEN COUNT(V.salary) > 1 THEN MIN(V.salary)
ELSE NULL
END AS 'SecondHighestSalary' FROM
(
SELECT TOP 2 SA.salary FROM
(
SELECT DISTINCT EM.salary
FROM Employee AS EM
) AS SA
ORDER BY SA.salary DESC
) AS V

Submission Detail

  • 8 / 8 test cases passed.
  • Runtime: 603 ms, faster than 85.83% of MS SQL Server online submissions for Second Highest Salary.
  • Memory Usage: 0B, less than 100.00% of MS SQL Server online submissions for Second Highest Salary.

177. Nth Highest Salary

1
2
3
4
5
6
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
DECLARE fromRow INT;
SET fromRow = N-1;
RETURN (select (select distinct Salary from Employee order by Salary desc limit 1 offset fromRow));
END

Submission Detail

  • 14 / 14 test cases passed.
  • Your runtime beats 86.66 % of mysql submissions.

178. Rank Scores

1
2
3
4
5
6
7
8
9
select a.Score,b.`Rank` from Scores a,
(
select t.Score,(@row_number:=@row_number+1) as `Rank` from
(
select distinct Score from Scores order by Score desc
) t,(SELECT @row_number:=0) t2
) b
where a.Score=b.Score
order by a.Score desc

Submission Detail

  • 10 / 10 test cases passed.
  • Your runtime beats 98.24 % of mysql submissions.

181. Employees Earning More Than Their Managers

1
select t.Name as Employee from Employee t where t.Salary>(select e.Salary from Employee e where e.Id=t.ManagerId)

Submission Detail

  • 14 / 14 test cases passed.
  • Your runtime beats 39.24 % of mysql submissions.

182. Duplicate Emails

1
2
select t.Email as Email from 
(select Email,count(Email) from Person group by Email having count(Email)>1) t

Submission Detail

  • 15 / 15 test cases passed.
  • Your runtime beats 76.83 % of mysql submissions.

183. Customers Who Never Order

1

1
2
select c.Name as Customers from Customers c where c.Id not in 
(select distinct o.CustomerId from Orders o)

Submission Detail

  • 12 / 12 test cases passed.
  • Your runtime beats 84.65 % of mysql submissions.

2

1
2
3
select c.Name as Customers from Customers c
left outer join Orders o on c.Id=o.CustomerId
where o.Id is null

Submission Detail

  • 12 / 12 test cases passed.
  • Your runtime beats 83.24 % of mysql submissions

196. Delete Duplicate Emails

虽然难度标为Easy,居然也被卡住了,还以为要用临时表,google关键字 mysql delete duplicate rows keep one搜到Delete all Duplicate Rows except for One in MySQL? [duplicate],原来是自己未完全理解mysql的delete关于多表删除的语法。

DELETE [LOW_PRIORITY] [QUICK] [IGNORE]
tbl_name[.*] [, tbl_name[.*]] ...
FROM table_references
[WHERE where_condition]

Or:

DELETE [LOW_PRIORITY] [QUICK] [IGNORE]
FROM tbl_name[.*] [, tbl_name[.*]] ...
USING table_references
[WHERE where_condition]

看来这种技术问题,google+stack overflow 一点就破,自己坚持独立思考在那里死磕纯属浪费时间。

1

1
delete p from Person as p, Person as t where p.Id>t.Id and p.Email=t.Email;

Submission Detail

  • 22 / 22 test cases passed.
  • Your runtime beats 18.50 % of mysql submissions.

2

1
delete p from Person as p, Person as t where p.Email=t.Email and p.Id>t.Id;

Submission Detail

  • 22 / 22 test cases passed.
  • Your runtime beats 83.82 % of mysql submissions.

3

1
delete p from Person as p inner join Person as t where p.Email=t.Email and p.Id>t.Id;

Submission Detail

  • 22 / 22 test cases passed.
  • Your runtime beats 80.14 % of mysql submissions.

180. Consecutive Numbers

被卡了好几天,百思不得其解,又开始怀疑是不是select还不足以,难道要用到游标与临时表之类,再琢磨下去也是浪费时间,遇到什么问题,就去问google,尤其是这种自己不会别人会的技术问题,搜 mysql consecutive queries 定位到 MySQL query for 3 consecutive integers between records,冥思苦想就是想不对路,一看到人家的解就恍然大悟,自己怎么会想不到这一点,看来自己的sql还是需要外部启发,没有点拨,自己就迷失在思维定势里了。

不过这题有点让人犯糊涂,如果id不连续呢?那是不是还得用计算列row_num?反正题意是id连续

1
2
3
select distinct t.Num as ConsecutiveNums from Logs t
where exists (select 1 from Logs x where x.Id-1=t.Id and x.Num=t.Num) and
exists(select 1 from Logs x where x.Id+1=t.Id and x.Num=t.Num);

Submission Detail

  • 21 / 21 test cases passed.
  • Your runtime beats 50.90 % of mysql submissions.

185. Department Top Three Salaries

琢磨了好几天也没思路,问题的难度标为hard,难道用select无法实现?难道要用到cursor与临时表?最后google -> mysql top 3 per group在Stack Overflow找到Get top n records for each group of grouped results,思路顿开,原来还是要用到查询结果序号的计算列,T-SQL与PL/SQL都有Rank()函数,mysql可以用变量模拟实现,在178. Rank Scores中已经用到,只是本题需要用到两个列,需要用两个@变量。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
select d.Name as Department,e.Name as Employee,b.Salary as Salary from 
(
select a.DepartmentId,a.Salary from
(
select t.DepartmentId,t.Salary,(@num:=if(@deptId = t.DepartmentId, @num +1, if(@deptId := t.DepartmentId, 1, 1))) as row_number from
(
select distinct DepartmentId,Salary from Employee
) t
CROSS JOIN (select @num:=0, @deptId:=null) c
order by t.DepartmentId,t.Salary desc
) a
where a.row_number<=3
) b
left outer join Employee e using(DepartmentId,Salary)
inner join Department d on e.DepartmentId=d.Id
order by b.DepartmentId,b.Salary desc;

Submission Detail

  • 20 / 20 test cases passed.
  • Your runtime beats 98.70 % of mysql submissions.

184. Department Highest Salary

也蒙了几天,group by得到部门max salary是显然的,怎么得到员工姓名?发现用部门id与salary同时作为join的条件就ok了,用using连接从句显得更自然。

1

1
2
3
4
select d.Name as Department,e.Name as Employee,t.Salary from Department d 
left outer join (select DepartmentId,Max(Salary) as Salary from Employee group by DepartmentId) t on t.DepartmentId=d.Id
inner join Employee e on t.Salary=e.Salary and t.DepartmentId=e.DepartmentId
order by t.Salary desc;

Submission Detail

  • 15 / 15 test cases passed.
  • Your runtime beats 77.87 % of mysql submissions.

2

1
2
3
4
select d.Name as Department,e.Name as Employee,t.Salary from Department d 
left outer join (select DepartmentId,Max(Salary) as Salary from Employee group by DepartmentId) t on d.Id=t.DepartmentId
inner join Employee e on e.DepartmentId=t.DepartmentId and e.Salary=t.Salary
order by t.Salary desc;

Submission Detail

  • 15 / 15 test cases passed.
  • Your runtime beats 87.87 % of mysql submissions.

3

1
2
3
4
select d.Name as Department,e.Name as Employee,t.Salary from Department d 
left outer join (select DepartmentId,Max(Salary) as Salary from Employee group by DepartmentId) t on d.Id=t.DepartmentId
inner join Employee e using(DepartmentId,Salary)
order by t.Salary desc;

Submission Detail

  • 15 / 15 test cases passed.
  • Your runtime beats 91.84 % of mysql submissions.

197. Rising Temperature

这题果然Easy, 不过自己还是在mysql手册里查了下函数DATEDIFF(expr1,expr2),不用google就ok了,在LeetCode第一次就通过了,此题的问题结构好像跟 180. Consecutive Numbers 类似。

想到人家刷LeetCode都是光用脑子调代码直接在网页上Run,而自己离不开IDE与数据库运行环境,人家那叫刷题,自己只是在做题。

1
select w.Id from Weather w, Weather t where datediff(w.RecordDate,t.RecordDate)=1 and w.Temperature>t.Temperature;

Submission Detail

  • 14 / 14 test cases passed.
  • Your runtime beats 90.59 % of mysql submissions.

262. Trips and Users

这题又耗了两天,一开始没看懂题意,虽然不能迅速做不出,倒也没怎么被卡住,不过免不了又要在纸上比划一下,还有在mysql上一遍遍执行验证想法,也没啥可以google的,提交Leetcode第一遍就通过了,没想到。自己对left outer join与right outer join的理解似乎有误,这两者是有区别的,自己之前似乎以为这两者是对称的。

1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
select b.Request_at as Day,round(IFNull(a.cancel_num,0)/b.total_num,2) as `Cancellation Rate` from 
(
select t.Request_at,count(*) as cancel_num from Trips t
where t.Client_Id in (select Users_Id from Users where Role='client' and Banned='No') and
t.Driver_Id in (select Users_Id from Users where Role='driver' and Banned='No') and
t.Status in ('cancelled_by_driver','cancelled_by_client') and t.Request_at between DATE '2013-10-01' and DATE '2013-10-03'
group by t.Request_at
) a right outer join
(
select t.Request_at,count(*) as total_num from Trips t
where t.Client_Id in (select Users_Id from Users where Role='client' and Banned='No') and
t.Driver_Id in (select Users_Id from Users where Role='driver' and Banned='No') and t.Request_at between DATE '2013-10-01' and DATE '2013-10-03'
group by t.Request_at
) b on b.Request_at=a.Request_at;

Submission Detail

  • 9 / 9 test cases passed.
  • Your runtime beats 82.92 % of mysql submissions.

2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
select a.Request_at as Day,round(IFNull(b.cancel_num,0)/a.total_num,2) as `Cancellation Rate` from 
(
select t.Request_at,count(*) as total_num from Trips t
where t.Client_Id in (select Users_Id from Users where Role='client' and Banned='No') and
t.Driver_Id in (select Users_Id from Users where Role='driver' and Banned='No') and t.Request_at between DATE '2013-10-01' and DATE '2013-10-03'
group by t.Request_at
) a left outer join
(
select t.Request_at,count(*) as cancel_num from Trips t
where t.Client_Id in (select Users_Id from Users where Role='client' and Banned='No') and
t.Driver_Id in (select Users_Id from Users where Role='driver' and Banned='No') and
t.Status in ('cancelled_by_driver','cancelled_by_client') and t.Request_at between DATE '2013-10-01' and DATE '2013-10-03'
group by t.Request_at
) b on b.Request_at=a.Request_at;

Submission Detail

  • 9 / 9 test cases passed.
  • Your runtime beats 61.34 % of mysql submissions.

595. Big Countries

这题确实Easy,or条件或用据说性能更好的 union (Set operations)

1

1
select name,population,area from World where area>3000000 or population>25000000;

Submission Detail

  • 4 / 4 test cases passed.

2

1
2
3
select name,population,area from World where area>3000000 
union
select name,population,area from World where population>25000000;

Submission Detail

  • 4 / 4 test cases passed.

596. Classes More Than 5 Students

这题也Easy,group by + having子句

1
2
3
4
select t.`class` as `class` from 
(
select `class`,count(distinct student) as n from courses group by `class` having n>=5
) t;

Submission Detail

  • 9 / 9 test cases passed.

601. Human Traffic of Stadium

这题又被卡了好几天,google也没搜到什么直接的线索,PL/SQL与T-SQL有分析函数ROW_NUMBER(), RANK(), and DENSE_RANK(),还以为需要mysql模拟这种功能。

卡在这一步里

select s.* from stadium s where s.people>=100 
and exists(select 1 from stadium t2 where t2.people>=100 and t2.`date`=DATE_SUB(s.`date`,INTERVAL 1 DAY)) 
and exists(select 1 from stadium t3 where t3.people>=100 and t3.`date`=DATE_ADD(s.`date`,INTERVAL 1 DAY));

最后发现用 join + union就好了,显示执行效率不高,可能还有更好的写法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
select x.* from 
(
select a.* from
(select s.* from stadium s where s.people>=100) a,
(
select s.* from stadium s where s.people>=100
and exists(select 1 from stadium t2 where t2.people>=100 and t2.id=s.id-1)
and exists(select 1 from stadium t3 where t3.people>=100 and t3.id=s.id+1)
) b
where a.id=b.id-1

union

select s.* from stadium s where s.people>=100
and exists(select 1 from stadium t2 where t2.people>=100 and t2.id=s.id-1)
and exists(select 1 from stadium t3 where t3.people>=100 and t3.id=s.id+1)

union

select c.* from
(
select s.* from stadium s where s.people>=100
and exists(select 1 from stadium t2 where t2.people>=100 and t2.id=s.id-1)
and exists(select 1 from stadium t3 where t3.people>=100 and t3.id=s.id+1)
) b,
(select s.* from stadium s where s.people>=100) c
where c.id=b.id+1
) x order by x.id;

Submission Detail

  • 14 / 14 test cases passed.
  • Your runtime beats 57.13 % of mysql submissions.

620. Not Boring Movies

这题确实Easy, 可以不假思索地写出SQL,但执行效率还是不够高,而且也查了下MOD函数与mod运算符。

1
select * from cinema where id%2=1 and description not like '%boring%' order by rating desc;

Submission Detail

  • 8 / 8 test cases passed.
  • Your runtime beats 72.39 % of mysql submissions.

Submission Detail

626. Exchange Seats

这题确实Medium,不难,但也不是很简单就能写出,inner join 与 outer join 进行union,执行效率还是不算高。

1
2
3
4
5
6
7
8
9
10
11
12
select * from 
(
select t1.id,t2.student from
(select * from seat where id%2=1) t1 join
(select * from seat where id%2=0) t2 on t1.id=t2.id-1

union

select IFNULL(t2.id,t1.id) as id,t1.student from
(select * from seat where id%2=1) t1 left outer join
(select * from seat where id%2=0) t2 on t1.id=t2.id-1
) t order by id;

Submission Detail

  • 12 / 12 test cases passed.
  • Your runtime beats 58.11 % of mysql submissions.

627. Swap Salary

算是Easy吧,不过还是看了下mysql的update语法,用IF()函数或者 case 都可以。

1

1
update salary set sex=IF(sex='m','f','m');

Submission Detail

  • 8 / 8 test cases passed.
  • Your runtime beats 53.28 % of mysql submissions.

2

1
update salary set sex=case sex when 'm' then 'f' when 'f' then 'm' end;

Submission Detail

  • 8 / 8 test cases passed.
  • Your runtime beats 49.22 % of mysql submissions.

Shell

195. Tenth Line

自己对linux shell果然是一无所知,连这个Easy的题也需要google 搜 linux sh read nth line,到 Bash tool to get nth line from a file,原来有个sed命令可以很简单地实现读第n行,此题存在一题多解,需要举一反三

1
2
3
#!/usr/bin/env bash

sed '10q;d' 'file.txt'

Submission Detail

  • 7 / 7 test cases passed.

193. Valid Phone Numbers

linux shell的题自己本来就不懂,只能从头学起,想也没用,不如google,linux shell regex phone number,直接出来个原题的答案,Regex Coding Exercise – Valid Phone Numbers,一个要点是正则表达式,一个要点是Linux的grep命令,学习了。这篇文章里说用 awksed 也行。题目要求用1行shell解决,也搜到个 Valid Phone Numbers with shell script 是用shell 的while及if语句来实现。

1
2
3
#!/usr/bin/env bash

grep -P "^((\([0-9]{3}\) )|([0-9]{3}\-))[0-9]{3}\-[0-9]{4}$" file.txt

Submission Detail

  • 26 / 26 test cases passed.

192. Word Frequency

这题标为medium,linux shell自己本来就不了解,又有点难度,独立思考不过是浪费时间,不如看看相关专题博客,google关键字linux shell word frequency,搜到 How to create a frequency list of every word in a file?,参考里面的左试右试总是不太对,又搜到个答案大全 Shell Coding Exercise – Word Frequency,人家高手一题多解给出N种异曲同工的方法,用了很多linux的内置功能命令比如cat, tr, awk, sed, sort,grep, uniq,自己也看不大懂,又参考评论里的解释改了下,原来是要sort两次,第二次逆序sort,终于运行通过,但效率不高。

1
sed -r 's/\s+/\n/g' words.txt | grep -v "^$" | sort | uniq -c | sort -r | awk '{print $2" "$1}'

Submission Detail

  • 14 / 14 test cases passed.

194. Transpose File

google关键字shell command transpose,搜到 An efficient way to transpose a file in Bash ,原来是要用awk写一小段程序,还没看懂,只有慢慢消息理解了。

Transposing rows and columns: 3 methods 则提到

  • Transposing rows and columns is indeed easy if you have the GNU datamash utility on your system.
  • The mighty text-processing program AWK can also do transposing.

对高手来说,方法多得很,殊途同归,条条道路通罗马。

自己的linux shell要学的东西比sql要多得多,sql好歹工作当中经常用,linux shell用得少就处处是问题,形式上先过上一遍,还得慢慢消化理解。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
awk '
{
for (i=1; i<=NF; i++) {
a[NR,i] = $i
}
}
NF>p { p = NF }
END {
for(j=1; j<=p; j++) {
str=a[1,j]
for(i=2; i<=NR; i++){
str=str" "a[i,j];
}
print str
}
}' file.txt

Submission Detail

  • 17 / 17 test cases passed.
  • Your runtime beats 11.53 % of bash submissions.