[leetcode]leetcode初体验
这几天把之前的设计模式回顾了一遍,整理了一点以前的项目。同学说,打算刷leetcode题目,也勾起了我的兴趣,索性也刷一些题目,再提高一些内功。刚开始进去,leetcode随机分配的题目,直接也就做了,在后来,按顺序做,现在做到了第五题。大概做了如下题目:
1. Two Sum
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
这个题目简单,直接上代码如下:
public int[] twoSum(int []nums,int target){
if(nums==null||nums.length==0){
return null;
}
int re[]=new int[2];
for(int i=0;i<nums.length;i++){
for(int j=i+1;j<nums.length;j++){
if(nums[i]+nums[j]==target){
re[0]=i+1;
re[1]=j+1;
}
}
}
return re;
}
2. Add Two Numbers
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
这个题也不难,主要考虑好进位就行,稍微费点功夫,代码如下:
private ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode re=null,head=re;
int tmp;
int flag=0;
while(l1!=null||l2!=null){
if(l1==null&&l2!=null){
tmp=l2.val+flag;
}else if(l1!=null&&l2==null){
tmp=l1.val+flag;
}else{
tmp=l1.val+l2.val+flag;
}
if(tmp/10!=0){//进位
ListNode lt=new ListNode(tmp%10);
flag=1;
if(l1==null&&l2!=null){
l1=null;
l2=l2.next;
}else if(l1!=null&&l2==null){
l1=l1.next;
l2=null;
}else{
l1=l1.next;
l2=l2.next;
}
if(re!=null){
re.next=lt;
re=re.next;
}else{
re=lt;
head=re;
}
//最后进位
if(l1==null&&null==l2){
ListNode lt1=new ListNode(tmp/10);
re.next=lt1;
re=re.next;
}
}else{
ListNode lt=new ListNode(tmp%10);
flag=0;
if(l1==null&&l2!=null){
l1=null;
l2=l2.next;
}else if(l1!=null&&l2==null){
l2=null;
l1=l1.next;
}else{
l1=l1.next;
l2=l2.next;
}
if(re!=null){
re.next=lt;
re=re.next;
}else{
re=lt;
head=re;
}
}
}
return head;
}
3.Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
这道题也不是太难,主要需要考虑到各种情况,刚开始的时候,没有考虑是一种包含元素的关系,直接用队列删除首元素,因此,AC不了。调整代码如下:
public int lengthOfLongestSubstring(String s) {
if(s.isEmpty()){
return 0;
}
int max=0,left=0;
Queue<Character> q=new LinkedList<Character>();
for(int i=0;i<s.length();i++){
if(q.contains(s.charAt(i))){
while(left<i&&s.charAt(left)!=s.charAt(i)){
q.remove(s.charAt(left));
left++;
}
left++;
}else{
q.offer(s.charAt(i));
max=Math.max(max,i-left+1);
}
}
return max;
}
4. Median of Two Sorted Arrays
There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
这个题初一看,很简单的样子,但是,确实一个难度很大的题目,想到了前几天用到的二路归并的思想。代码如下:
public double findMedianSortedArrays(int nums1[], int nums2[]) {
if((nums1.length+nums2.length)%2==1)
return merge(nums1,nums2,0,nums1.length-1,0,nums2.length-1,(nums1.length+nums2.length)/2+1);
else
return (merge(nums1,nums2,0,nums1.length-1,0,nums2.length-1,(nums1.length+nums2.length)/2)
+merge(nums1,nums2,0,nums1.length-1,0,nums2.length-1,(nums1.length+nums2.length)/2+1))/2.0;
}
private int merge(int A[], int B[], int i, int i2, int j, int j2, int k){
int m = i2-i+1;
int n = j2-j+1;
if(m>n)
return merge(B,A,j,j2,i,i2,k);
if(m==0)
return B[j+k-1];
if(k==1)
return Math.min(A[i],B[j]);
int posA = Math.min(k/2,m);
int posB = k-posA;
if(A[i+posA-1]==B[j+posB-1])
return A[i+posA-1];
else if(A[i+posA-1]<B[j+posB-1])
return merge(A,B,i+posA,i2,j,j+posB-1,k-posA);
else
return merge(A,B,i,i+posA-1,j+posB,j2,k-posB);
}
130. Surrounded Regions
Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'.
A region is captured by flipping all 'O's into 'X's in that surrounded region.
For example,
X X X X
X O O X
X X O X
X O X X
After running your function, the board should be:
X X X X
X X X X
X X X X
X O X X
这个题主要是图的深度优先和广度优先遍历问题,在深度优先的时候,使用递归实现的时候,是不能AC的,会报栈溢出的错误,因此修改为了非递归的方式:
public void solve(char[][] board) {
if(board==null||board.length==0){
return;
}
int m=board.length;
int n=board[0].length;
for(int i=0;i<m;i++){
if(board[i][0]=='O'){
dfs(board,i,0);
}
if(board[i][n-1]=='O'){
dfs(board,i,n-1);
}
}
for(int j=0;j<n;j++){
if(board[0][j]=='O'){
dfs(board,0,j);
}
if(board[m-1][j]=='O'){
dfs(board,m-1,j);
}
}
print(board);
System.out.println("===============");
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(board[i][j]=='O'){
board[i][j]='X';
}else if(board[i][j]=='#'){
board[i][j]='O';
}
}
}
print(board);
}
/**
* @Title dfs
* @Description 采用递归会报java.lang.StackOverflowError错误。非递归实现的时候,在if中加入continue。之后得不到正确结果。
* @param board
* @param i
* @param j
* @Return void
* @Throws
* @user Administrator
* @Date 2016年1月24日
*/
public void dfs(char[][]board,int i,int j){
//非递归实现
Stack<Pos> s=new Stack<Pos>();
Pos pos=new Pos(i,j);
s.push(pos);
board[i][j]='#';
int m=board.length;
int n=board[0].length;
while(!s.isEmpty()){
Pos top=s.pop();
if(top.x>0&&board[top.x-1][top.y]=='O'){
Pos up=new Pos(top.x-1,top.y);
s.push(up);
board[up.x][up.y]='#';
}
if(top.x<m-1&&board[top.x+1][top.y]=='O'){
Pos down=new Pos(top.x+1,top.y);
s.push(down);
board[down.x][down.y]='#';
}
if(top.y>0&&board[top.x][top.y-1]=='O'){
Pos left=new Pos(top.x,top.y-1);
s.push(left);
board[left.x][left.y]='#';
}
if(top.y<n-1&&board[top.x][top.y+1]=='O'){
Pos right=new Pos(top.x,top.y+1);
s.push(right);
board[right.x][right.y]='#';
}
}
}
private class Pos{
int x,y;
public Pos(int x,int y){
this.x=x;
this.y=y;
}
};
206. Reverse Linked List
Reverse a singly linked list.
这个题很简单:
public ListNode reverseList(ListNode head) {
ListNode re=null;
Stack<ListNode> s=new Stack<ListNode>();
while(head!=null){
ListNode tmp=new ListNode(head.val);
s.push(tmp);
head=head.next;
}
ListNode st=null,h=re;
while(!s.isEmpty()){
st=s.pop();
if(re==null){
re=st;
h=re;
}else{
re.next=st;
re=re.next;
}
}
return h;
}
328. Odd Even Linked List
Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.
You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.
Example:
Given 1->2->3->4->5->NULL,
return 1->3->5->2->4->NULL.
这个问题也不算太难:
public ListNode oddEvenList(ListNode head) {
if(head==null)return head;
ListNode odd=head,even=head.next,evenHead=even;
while(odd.next!=null&&even.next!=null){
odd.next=even.next;
odd=odd.next;
even.next=odd.next;
even=even.next;
}
odd.next=evenHead;
return head;
}
未完待续……
[leetcode]leetcode初体验的更多相关文章
- .NET平台开源项目速览(15)文档数据库RavenDB-介绍与初体验
不知不觉,“.NET平台开源项目速览“系列文章已经15篇了,每一篇都非常受欢迎,可能技术水平不高,但足够入门了.虽然工作很忙,但还是会抽空把自己知道的,已经平时遇到的好的开源项目分享出来.今天就给大家 ...
- Xamarin+Prism开发详解四:简单Mac OS 虚拟机安装方法与Visual Studio for Mac 初体验
Mac OS 虚拟机安装方法 最近把自己的电脑升级了一下SSD固态硬盘,总算是有容量安装Mac 虚拟机了!经过心碎的安装探索,尝试了国内外的各种安装方法,最后在youtube上找到了一个好方法. 简单 ...
- Spring之初体验
Spring之初体验 Spring是一个轻量级的Java Web开发框架,以IoC(Inverse of Control 控制反转)和 ...
- Xamarin.iOS开发初体验
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKwAAAA+CAIAAAA5/WfHAAAJrklEQVR4nO2c/VdTRxrH+wfdU84pW0
- 【腾讯Bugly干货分享】基于 Webpack & Vue & Vue-Router 的 SPA 初体验
本文来自于腾讯bugly开发者社区,非经作者同意,请勿转载,原文地址:http://dev.qq.com/topic/57d13a57132ff21c38110186 导语 最近这几年的前端圈子,由于 ...
- 【Knockout.js 学习体验之旅】(1)ko初体验
前言 什么,你现在还在看knockout.js?这货都已经落后主流一千年了!赶紧去学Angular.React啊,再不赶紧的话,他们也要变out了哦.身旁的90后小伙伴,嘴里还塞着山东的狗不理大蒜包, ...
- 在同一个硬盘上安装多个 Linux 发行版及 Fedora 21 、Fedora 22 初体验
在同一个硬盘上安装多个 Linux 发行版 以前对多个 Linux 发行版的折腾主要是在虚拟机上完成.我的桌面电脑性能比较强大,玩玩虚拟机没啥问题,但是笔记本电脑就不行了.要在我的笔记本电脑上折腾多个 ...
- 百度EChart3初体验
由于项目需要在首页搞一个订单数量的走势图,经过多方查找,体验,感觉ECharts不错,封装的很细,我们只需要看自己需要那种类型的图表,搞定好自己的json数据就OK.至于说如何体现出来,官网的教程很详 ...
- Python导出Excel为Lua/Json/Xml实例教程(二):xlrd初体验
Python导出Excel为Lua/Json/Xml实例教程(二):xlrd初体验 相关链接: Python导出Excel为Lua/Json/Xml实例教程(一):初识Python Python导出E ...
- Docker初体验
## Docker初体验 安装 因为我用的是mac,所以安装很简单,下载dmg下来之后拖拽安装即可完成. 需要注意的就是由于之前的docker是基于linux开发,不支持mac,所以就出现了docke ...
随机推荐
- Asp.net C# 把 Datatable转换成JSON 字符串
First of all, we have to fetch the records from the database (MS Sqlserver) into the C# DataTable, o ...
- jquery缓存使用jquery.cookies.2.2.0.min.js
$.cookies.set(key, obj, { hoursToLive: 2}); key标识的键 , obj存入的值可以缓存json对象, hoursToLive 缓存小时数 $.cookies ...
- 移动端Web开发调试之Chrome远程调试(Remote Debugging)
比如手机钉钉调试页面,下面是一位同学整理的链接: http://blog.csdn.net/freshlover/article/details/42528643/ 如果inspect 后,一直空白, ...
- SQL 归来
1. PL/SQL 转义 select order#, ……… from **** select col1 from A where col2 like '%\_keywors%' escape ' ...
- OpenFOAM&Gmsh&CFD圆柱绕流(两个圆柱)
问题: 圆柱绕流问题,模拟仿真有两个圆柱.一个源的流体变化情况. 解决步骤: 1.使用Gmsh画出网格,并保存cylindertwo.msh 2.以Cavity为基础创建新的Case:Cylinder ...
- 如何实现 javascript “同步”调用 app 代码
在 App 混合开发中,app 层向 js 层提供接口有两种方式,一种是同步接口,一种一异步接口(不清楚什么是同步的请看这里的讨论).为了保证 web 流畅,大部分时候,我们应该使用异步接口,但是某些 ...
- react+redux官方实例TODO从最简单的入门(6)-- 完结
通过实现了增-->删-->改-->查,对react结合redux的机制差不多已经了解,那么把剩下的功能一起完成吧 全选 1.声明状态,这个是全选状态 2.action约定 3.red ...
- PageRank的java实现
一个网络(有向带权图)中节点u的PageRank的计算公式: PR(u)表示节点u的PageRank值,d为衰减因子(damping factor)或阻尼系数,一般取d=0.85,N为网络中的节点总数 ...
- CSS3 media 入门
css3 media 严格来说是自适应布局 对不同的屏幕(正确的说应该是) 写不同的css样式.而流式布局 则才算是响应式布局. css3 media 语法: @media mediatype a ...
- Web项目使用Oracle.DataAccess.dll 类库连接oracle数据库
首先我用的工具是oracle 32位免安装版+Oracle.DataAccess.dll 32位 文件版本4.121.1.0+vs2013 +win7 64位 Oracle.DataAccess.d ...