LeetCode 2
No1
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
个人:
public int searchInsert(int[] nums, int target) {
for(int i=0;i<nums.length;i++){
if(nums[i]>=target){
return i;
}
}
return nums.length;
}
优秀代码: public int searchInsert(int[] A, int target) { int low = 0, high = A.length-1;
while(low<=high){
int mid = (low+high)/2;
if(A[mid] == target) return mid;
else if(A[mid] > target) high = mid-1;
else low = mid+1;
}
return low;
}
No2
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.
public void merge(int[] nums1, int m, int[] nums2, int n) {
int length=m+n-1,x=m-1,y=n-1;
while(x>-1 && y>-1){
nums1[length--] = (nums1[x]>nums2[y]) ? nums1[x--] : nums2[y--];
}
while(y>-1){
nums1[length--]=nums2[y--];
}
}
No3
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example, "A man, a plan, a canal: Panama" is a palindrome. "race a car" is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
public static boolean isPalindrome(String s) {
char[] str=s.toLowerCase().toCharArray();
StringBuilder stringBuilder=new StringBuilder();
for(int i=0;i<str.length;i++){
if(Character.isLetterOrDigit(str[i])&&str[i]!=' '){
stringBuilder.append(str[i]);
}
}
str=stringBuilder.toString().toCharArray();
if(str.length<=1)return true;
int start=0;
int length=str.length-1;
while(start<length){
if(str[start]!=str[length]){
return false;
}else {
start++;
length--;
}
}
if(start>=length) return true;
return false;
}
public static boolean isPalindrome(String s) {
String str=s.replaceAll("[^A-Za-z0-9]","").toLowerCase();
String stringBUffer=new StringBuffer(str).reverse().toString();
return str.equals(stringBUffer);
}
No3
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
public int maxDepth(TreeNode root) {
if(root==null){
return 0;
}
return 1+Math.max(maxDepth(root.left),maxDepth(root.right));
}
小心得:在求有一定规律结构时 可用递归去实现 而不用每个分支都储存 然后求size 。很屎的想法
No4
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode p1 = l1, p2 = l2;
ListNode result = new ListNode(0);
ListNode pk=result;
int c = 0;
while (p1 != null || p2 != null || c == 1) {
int num1 =( p1 == null ? 0 : p1.val);
int num2 =( p2 == null ? 0 : p2.val);
int k = num1 + num2 + c;
c = k / 10;
pk.next = new ListNode(k % 10);
pk = pk.next;
if (p1 != null) {p1 = p1.next;}
if (p2 != null) {p2 = p2.next;}
}
return result.next;//不能反回pk.next; pk仅将指针只想result的堆 所以数据还存在result指向的堆 否则报错
}
LeetCode 2的更多相关文章
- 我为什么要写LeetCode的博客?
# 增强学习成果 有一个研究成果,在学习中传授他人知识和讨论是最高效的做法,而看书则是最低效的做法(具体研究成果没找到地址).我写LeetCode博客主要目的是增强学习成果.当然,我也想出名,然而不知 ...
- LeetCode All in One 题目讲解汇总(持续更新中...)
终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 477 Total Hamming Distance ...
- [LeetCode] Longest Substring with At Least K Repeating Characters 至少有K个重复字符的最长子字符串
Find the length of the longest substring T of a given string (consists of lowercase letters only) su ...
- Leetcode 笔记 113 - Path Sum II
题目链接:Path Sum II | LeetCode OJ Given a binary tree and a sum, find all root-to-leaf paths where each ...
- Leetcode 笔记 112 - Path Sum
题目链接:Path Sum | LeetCode OJ Given a binary tree and a sum, determine if the tree has a root-to-leaf ...
- Leetcode 笔记 110 - Balanced Binary Tree
题目链接:Balanced Binary Tree | LeetCode OJ Given a binary tree, determine if it is height-balanced. For ...
- Leetcode 笔记 100 - Same Tree
题目链接:Same Tree | LeetCode OJ Given two binary trees, write a function to check if they are equal or ...
- Leetcode 笔记 99 - Recover Binary Search Tree
题目链接:Recover Binary Search Tree | LeetCode OJ Two elements of a binary search tree (BST) are swapped ...
- Leetcode 笔记 98 - Validate Binary Search Tree
题目链接:Validate Binary Search Tree | LeetCode OJ Given a binary tree, determine if it is a valid binar ...
- Leetcode 笔记 101 - Symmetric Tree
题目链接:Symmetric Tree | LeetCode OJ Given a binary tree, check whether it is a mirror of itself (ie, s ...
随机推荐
- Python内置函数(12)——str
英文文档: class str(object='') class str(object=b'', encoding='utf-8', errors='strict') Return a string ...
- Linux进程管理:后台启动进程和任务管理命令
一.为什么要使程序在后台执行 我们的应用有时候要运行时间很长,如:几个小时甚至几个星期,我们可以让程序在后台一直跑. 让程序在后台运行的好处有: 终端关机不影响后台进程的运行.(不会终端一关机或者网络 ...
- spring-oauth-server实践:授权方式三:PASSWORD模式下 authorities:ROLE_{user.privillege}, ROLE_USER
一.数据库配置 1.oauth_client_details 2.user_ 3.user_privillege 二.password模式 授权过程 1.授权者granter和请求参数 Resourc ...
- JSON(四)——异步请求中前后端使用Json格式的数据进行交互
json格式的数据广泛应用于异步请求中前后端的数据交互,本文主要介绍几种使用场景和使用方法. 一,json格式字符串 <input type="button" id=&quo ...
- O(logN)中logN的底数
转载:http://blog.csdn.net/jdbc/article/details/42173751 问题: 无论是计算机算法概论.还是数据结构书中, 关于算法的时间复杂度很多都用包含O(log ...
- python当中的生成器
最近身边的朋友都在问我迭代器是什么回事,经常跟大家一起讨论python的迭代器,一点点的我觉着自己有了更深一层的理解.我写下这篇文章,希望能对懵懵懂懂的好伙伴有些帮助~ 我也不是什么能人,难免说错一些 ...
- ShellCode瘦身的艺术0_HASH
写在前面的话: 前面几篇文章,我们介绍了如何获取kernerl32.dll导出函数地址的方法: 并在此基础上,编写了ShellCode,实现了动态加载DLL以及解析API地址: 但是,似乎还称不上Pe ...
- 网络配置及shell基础
一:集群已做完 二:临时配置网络(ip,网关,dns)+永久配置 临时配置网络: ip: [root@localhost ~]# ifconfig [root@localhost ~]# ifc ...
- 1020关于MYCAT的安装和使用总结
第一部分 读写分离配置 转自:http://www.51testing.com/html/34/369434-3686088.html 使用Mycat 做简单的读写分离(一) 原本使用的是amoeba ...
- [原创软件]Maya报错窗口监测器
软件主要功能: 监测Maya软件运行状态,如弹出报错窗口,则自动点击关闭 程序界面截图: 开发环境及语言: c# .NET Framework 4.0 Visual Studio 2015 更新日志: ...