LeetCode解题报告—— Linked List Cycle II & Reverse Words in a String & Fraction to Recurring Decimal
1. Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
思路:想法是利用两指针,一个每次移动一步,另一个每次移动两步,如果存在环则这两个指针一定会相遇(这里可以在纸上画一下,因为后一个指针移动比前一个指针快,当后一个指针在环中来到前一个指针的前面时只有两种情况,在它前一个或者前两个,无论那种情况都能走到一起)。但是并不知道具体会在第几圈相遇,现在到了数学分析的时候了:https://leetcode.com/problems/linked-list-cycle-ii/discuss/44793/O(n)-solution-by-using-two-pointers-without-change-anything
ListNode *detectCycle(ListNode *head) {
if (head == NULL || head->next == NULL) return NULL;
ListNode* firstp = head;
ListNode* secondp = head;
bool isCycle = false;
while(firstp != NULL && secondp != NULL) {
firstp = firstp->next;
if (secondp->next == NULL) return NULL;
secondp = secondp->next->next;
if (firstp == secondp) { isCycle = true; break; }
}
if(!isCycle) return NULL;
firstp = head;
while( firstp != secondp) {
firstp = firstp->next;
secondp = secondp->next;
}
return firstp;
}
2. Reverse Words in a String
Given an input string, reverse the string word by word.
Example:
Input: "the sky is blue",
Output: "blue is sky the".
Note:
- A word is defined as a sequence of non-space characters.
- Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
- You need to reduce multiple spaces between two words to a single space in the reversed string.
String[] parts = s.trim().split("\\s+");
String out = "";
for (int i = parts.length - 1; i > 0; i--) {
out += parts[i] + " ";
}
return out + parts[0];
注意的是上面的正则表达式的用法,\s 匹配任何不可见字符,包括空格、制表符、换页符等等。等价于[ \f\n\r\t\v],后面的 + 表示匹配一个或多个,然后就是在java中使用正则前面要多加个反斜杠。
3. Fraction to Recurring Decimal
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part is repeating, enclose the repeating part in parentheses.
Example 1:
Input: numerator = 1, denominator = 2
Output: "0.5"
Example 2:
Input: numerator = 2, denominator = 1
Output: "2"
Example 3:
Input: numerator = 2, denominator = 3
Output: "0.(6)"
思路:难点在于小数部分的判断,可以用一个map,key是当前的被除数,value是当前计算结果的数字长度,如果在计算过程中key和之前的key相等,因为除数一直不变,所以这是开始循环,那么就要在上一个key所对应的value处插入 ( 符号,然后在末尾插入 ) 符号。
public class Solution {
public String fractionToDecimal(int numerator, int denominator) {
if (numerator == 0) {
return "0";
}
StringBuilder res = new StringBuilder();
// "+" or "-"
res.append(((numerator > 0) ^ (denominator > 0)) ? "-" : ""); // 判断正负,异号的情形才是负
long num = Math.abs((long)numerator);
long den = Math.abs((long)denominator);
// integral part
res.append(num / den); // 先求出整数部分
num %= den; // 求余数
if (num == 0) {
return res.toString();
}
// fractional part
res.append(".");
HashMap<Long, Integer> map = new HashMap<Long, Integer>();
map.put(num, res.length()); // 将余数作为key加入到map中
while (num != 0) {
num *= 10;
res.append(num / den); // 上面num乘10是因为这里要取小数点最后一位的后一位的除后的整数,否则num/den就一直是0
num %= den; // 求余数
if (map.containsKey(num)) { // 如果余数和某一轮的被除数一样,因为除数一直不变,那么则表明开始无限循环了
int index = map.get(num); // 取开始发生无限循环时res的长度已确定插入 ( 符号的位置
res.insert(index, "(");
res.append(")");
break;
}
else {
map.put(num, res.length()); // 如果没开始无限循环,则要记录当前除后结果数字的长度,以记录插入括号的位置
}
}
return res.toString();
}
}
LeetCode解题报告—— Linked List Cycle II & Reverse Words in a String & Fraction to Recurring Decimal的更多相关文章
- LeetCode解题报告:Linked List Cycle && Linked List Cycle II
LeetCode解题报告:Linked List Cycle && Linked List Cycle II 1题目 Linked List Cycle Given a linked ...
- leetcode解题报告(25):Reverse Words in a String III
描述 Given a string, you need to reverse the order of characters in each word within a sentence while ...
- 【LeetCode练习题】Linked List Cycle II
Linked List Cycle Given a linked list, determine if it has a cycle in it. Follow up:Can you solve it ...
- 【LeetCode】142. Linked List Cycle II (2 solutions)
Linked List Cycle II Given a linked list, return the node where the cycle begins. If there is no cyc ...
- 【LeetCode】142. Linked List Cycle II
Difficulty:medium More:[目录]LeetCode Java实现 Description Given a linked list, return the node where t ...
- 【LeetCode】142. Linked List Cycle II 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 双指针 set 日期 题目地址:https://le ...
- leetcode解题报告(27):Reverse Linked List
描述 Reverse a singly linked list. 分析 一开始写的时候总感觉没抓到要点,然后想起上数据结构课的教材上有这道题,翻开书一看完就回忆起来了,感觉解法挺巧妙的,不比讨论区的答 ...
- LeetCode OJ 142. Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return null. Note ...
- LeetCode解题报告—— Word Search & Subsets II & Decode Ways
1. Word Search Given a 2D board and a word, find if the word exists in the grid. The word can be con ...
随机推荐
- Consul入门
推荐: Consul 原理和使用简介 启动:consul agent -server -bootstrap-expect 1 -data-dir /tmp/consul -node Litao-Mac ...
- JavaScript定义类与对象的一些方法
最近偶然碰到有朋友问我"hoisting"的问题.即在js里所有变量的声明都是置顶的,而赋值则是在之后发生的.可以看看这个例子: 1 var a = 'global'; 2 (fu ...
- linux 下文件重命名/移动/复制命令(转)
linux 下文件重命名/移动/复制命令(转) linux下重命名文件:使用mv命令就可以了, 例:要把名为:abc 重命名为:123 可以这样操作: 重命名:MV命令 1.进入你的文件目录,运行 ...
- 《时间序列分析及应用:R语言》读书笔记--第一章 引论
"春节假期是难得的读书充电的时间."--来自某boss.假期能写多少算多少,一个是题目中的这本书,另一个是<python核心编程>中的高级部分,再一个是拖着的<算 ...
- HDU 5645
DZY Loves Balls Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others ...
- sudoers文件配置
http://note.drx.tw/2008/01/linuxsudo.html foobar ALL=(ALL) ALL 現在讓我們來看一下那三個 ALL 到底是什麼意思.第一個 ALL 是指網路 ...
- javascript实现正整数分数约分
//m,n为正整数的分子和分母 function reductionTo(m, n) { var arr = []; if (!isInteger(m) || !isInteger(n)) { con ...
- generatorConfiguration配置文件及其详细解读
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE generatorConfiguratio ...
- 【BZOJ4236】JOIOJI [DP]
JOIOJI Time Limit: 10 Sec Memory Limit: 256 MB[Submit][Status][Discuss] Description JOIOJI桑是JOI君的叔叔 ...
- hdu 2059 龟兔赛跑(动态规划DP)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2059 龟兔赛跑 Time Limit: 1000/1000 MS (Java/Others) M ...