数组
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。
请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
public static boolean Solution(int target, int[][] a){
if(a == null || a.length == 0){
return false;
}
boolean found = false;
int rows = a.length;//行数
int columns = a[0].length;//列数
int r = 0;
int c = columns -1;
while(r <= rows-1 && c >= 0 ){
if(a[r][c] == target ){
found = true;
break;
}else if (a[r][c] > target){
c--;
}else{
r++;
}
}
return found;
}
链表
输入一个链表,从尾到头打印链表每个节点的值
public class PrintListFromTailToHead {
ArrayList<Integer> temp = new ArrayList<Integer>();
public ArrayList<Integer> solution1(ListNode listNode){
if(listNode != null){
solution1(listNode.next);
temp.add(listNode.val);
}
return temp;
}
public ArrayList<Integer> solution2(ListNode listNode){
while (listNode != null){
temp.add(0,listNode.val);
listNode = listNode.next;
}
return temp;
}
public ArrayList<Integer> solution3(ListNode listNode){
Stack<Integer> stack = new Stack<Integer>();
while (listNode != null){
stack.push(listNode.val);
listNode = listNode.next;
}
while(!stack.isEmpty()){
temp.add(stack.pop());
}
return temp;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
字符串
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
public static String solution1 (StringBuffer str){
//找出字符串中所有的空格数
int space = 0;
for(int i=0;i<str.length();i++){
if(str.charAt(i) == ' '){
space++;
}
}
//" "替换成"%20"字符串的长度要增加space*2个
int oldIndex = str.length() - 1;
int newLength = str.length() + 2 * space;
int newIndex = newLength - 1;
str.setLength(newLength);
//从后往前遍历,如果oldIndex = newIndex证明字符串中没有空格,不需要替换
while(oldIndex >= 0 && oldIndex < newIndex){
if(str.charAt(oldIndex) == ' '){
str.setCharAt(newIndex--,'0');
str.setCharAt(newIndex--,'2');
str.setCharAt(newIndex--, '%');
space--;
//如果剩余部分没有空格,则不需要继续处理下去
if(space == 0){
break;
}
}else{
str.setCharAt(newIndex--, str.charAt(oldIndex));
}
oldIndex--;
}
return str.toString();
}
public static String solution2 (StringBuffer str){
StringBuffer temp = new StringBuffer();
for(int i=0;i<str.length();i++){
if (str.charAt(i) == ' '){
temp.append("%20");
}else{
temp.append(str.charAt(i));
}
}
return temp.toString();
}