lintcode是朋友推荐的一个算法刷题网站,可以开拓自己的算法视野
刚开始刷题,先找两个简单的算法试试水
试题一、 矩阵面积
描述:
实现一个矩阵类Rectangle,包含如下的一些成员变量与函数:
两个共有的成员变量 width 和 height 分别代表宽度和高度。
一个构造函数,接受2个参数 width 和 height 来设定矩阵的宽度和高度。
一个成员函数 getArea,返回这个矩阵的面积
样例
Rectangle rec = new Rectangle(3, 4);
rec.getArea(); // should get 12
实现(java)
public class Rectangle {
/*
* Define two public attributes width and height of type int.
*/
// write your code here
public int width;
public int height;
/*
* Define a constructor which expects two parameters width and height here.
*/
// write your code here
public Rectangle(int width,int height){
this.width = width;
this.height = height;
}
/*
* Define a public method `getArea` which can calculate the area of the
* rectangle and return.
*/
// write your code here
public int getArea(){
return this.width * this.heigth;
}
}
理解:
题目很简单这里就不解释了
试题二、二叉树的最大节点
描述
在二叉树中寻找值最大的节点并返回
数据
1
/ \
-5 2
/ \ / \
0 3 -4 -5
代码
public class Solution {
/*
* @param root: the root of tree
* @return: the max node
*/
private TreeNode mNode;
public TreeNode maxNode(TreeNode root) {
// write your code here
seachTree(root);
return mNode;
}
public void seachTree(TreeNode node){
if(node == null)
return ;
if(minNode == null){
mNode = node;
}else if(node.val > mNode.val ){
mNode = node;
}
seachTree(node.left );
seachTree(node.right );
}
}
理解:
结合二叉树递归查询,挑选出遍历出来的最大节点
试题三、整数排序
描述:
给一组整数,按照升序排序,使用选择排序,冒泡排序,插入排序或者任何 O(n2) 的排序算法
代码:
public class Solution {
/*
* @param A: an integer array
* @return:
*/
public void sortIntegers(int[] A) {
// write your code here
int temp ;
int length = A.length;
for(int i = 0; i< length ; i++){
for(int j = i+1 ; j < length ; j++ ){
if(A[i]>A[j]){
temp = A[i];
A[i] = A[j];
A[j] = temp;
}
}
}
}
}
解题思路(冒泡):
数组的排序问题,冒泡、选择、插入等算法均可实现
试题四、删除链表中的元素
描述:
删除链表中等于给定值val
的所有节点。
样例:
给出链表 1->2->3->3->4->5->3
, 和 val = 3
, 你需要返回删除3之后的链表:1->2->4->5
。
解题思路:
循环遍历链表,删除符合条件的元素,
难点:设计删除链表元素节点的需要考虑节点两种种情况:
1、当前节点是否为空
2、下个节点是否为空
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
/*
* @param head: a ListNode
* @param val: An integer
* @return: a ListNode
*/
public ListNode removeElements(ListNode head, int val) {
// write your code here
ListNode a = head;
ListNode tem = null;
if(head == null){
return null;
}
while(a.next!=null){
if(a.next.val == val){
if(a.next.next==null){
a.next = null;
break;
}else{
a.next = a.next.next;
}
}else{
a = a.next;
}
}
if(head.val == val){
return head.next;
}
return head;
}
}