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 ...
随机推荐
- libudev使用说明书
转http://blog.csdn.net/coroutines/article/details/38067805 1. 初始化 首先调用udev_new,创建一个udev library conte ...
- Linux安装cx_Oracle
安装依赖包 yum -y install gcc python-devel 确认以下变量都已经设置好了 export ORACLE_HOME=/home/oracle/app/oracle/produ ...
- javascript实用例子
js学习笔记,别错过!很有用的. /////////////////////////////////////////////////////////////////////////////////// ...
- Educational Codeforces Round 6 B
B. Grandfather Dovlet’s calculator time limit per test 1 second memory limit per test 256 megabytes ...
- [解决] HiveServer2中使用jdbc访问hbase时导致ZooKeeper连接持续增加的解决
最近在监控中发现HiveServer2连接到zookeeper里的连接持续上涨,很奇怪,虽然知道HiveServer2支持并发连接,使用ZooKeeper来管理Hive表的读写锁,但我们的环境并不需要 ...
- Python爬虫学习笔记之点触验证码的识别
代码: Chaojiying.py: #!/usr/bin/env python # coding:utf-8 import requests from hashlib import md5 clas ...
- Python爬虫学习笔记之极限滑动验证码的识别
代码: import time from io import BytesIO from PIL import Image from selenium import webdriver from sel ...
- cnn 卷积神经网络 人脸识别
卷积网络博大精深,不同的网络模型,跑出来的结果是不一样,在不知道使用什么网络的情况下跑自己的数据集时,我建议最好去参考基于cnn的手写数字识别网络构建,在其基础上进行改进,对于一般测试数据集有很大的帮 ...
- el-date-picker 日期格式化 yyyy-MM-dd
<el-date-picker format="yyyy-MM-dd" v-model="dateValue" type="date" ...
- Linux命令--hostname和uname
hostname命令 hostname命令用于显示和设置系统的主机名称.环境变量HOSTNAME也保存了当前的主机名.在使用hostname命令设置主机名后,系统并不会永久保存新的主机名,重新启动机器 ...