刚开始做LeetCode上的题目,也是首次用java做算法题目,一开始无从下手,看了几个Discuss,做了几道简单题目。
7. Reverse Integer
https://leetcode.com/problems/reverse-integer/
很简单的题目,但是忘记超出int范围的处理。
这种方法值得学习:
if (Integer.MAX_VALUE / 10 < res || (Integer.MAX_VALUE- x % 10) < res * 10) {
return 0;
}
public class Solution {
public int reverse(int x) {
boolean flag = false;
if(x < 0)
{
x = -x;
flag = true;
}
long r = 0;
while(x != 0)
{
r = (r * 10 + x %10);
x /= 10;
}
if(flag)
r = -r;
if(r > Integer.MAX_VALUE || r < Integer.MIN_VALUE)
return 0;
return (int)r;
}
}
8 String to Integer (atoi)
https://leetcode.com/problems/string-to-integer-atoi/
注意的地方很多:(当然我没有想这么全面)
1.数字前面有空格 如s=“ 123456”
2.数字前出现了不必要或多于的字符导致数字认证错误,输出0 如s=“ b1234” ,s=“ ++1233” , s=“ +-1121”
3.数字中出现了不必要的字符,返回字符前的数字 如s=“ 12a12” , s=“ 123 123”
4.数字越界 超过了范围(-2147483648–2147483647) 若超过了负数的 输出-2147483648 超过了正数的输出2147483647
在科普一个知识点,倘若某个数超过了2147483647则会变为负数,反过来一样
public class Solution {
public int myAtoi(String str) {
int num = 0,i = 0;
str = str.trim();//去掉多余空格
int len = str.length();
boolean flag = true;
if(i < len && str.charAt(i) == '-')//判断正负
{
i++;
flag = false;
}else if(i < len && str.charAt(i) == '+')
{
i++;
flag = true;
}
while(i < len && str.charAt(i) >= '0' && str.charAt(i) <= '9')
{
int n = (int)(str.charAt(i) - '0');
if(flag && num > (Integer.MAX_VALUE - n)/10)//边界值判断
return Integer.MAX_VALUE;
if(!flag && num > -((Integer.MIN_VALUE + n)/10))
return Integer.MIN_VALUE;
num = num * 10 + n;
i++;
}
if(!flag)
num = 0 - num;
return num;
}
}
21 Merge Two Sorted Lists
https://leetcode.com/problems/merge-two-sorted-lists/
我用的方法是顺序遍历
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = null,p = null;
while(l1 != null && l2 != null)
{
if(l1.val <= l2.val)
{
if(head == null)
head = l1;
else
p.next = l1;
p = l1;
l1 = l1.next;
}else
{
if(head == null)
head = l2;
else
p.next = l2;
p = l2;
l2 = l2.next;
}
}
if(l1 != null)
{
if(head == null)
head = l1;
else
p.next = l1;
}
if(l2 != null)
{
if(head == null)
head = l2;
else
p.next = l2;
}
return head;
}
}
还有一种递归方式
if(l1 == null) return l2;
if(l2 == null) return l1;
if(l1.val < l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists(l2.next, l1);
return l2;
}