二维数组中查找,替换空格,倒序输出链表

1.题目描述
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数
解题思路
因为二维数组是左到右递增的顺序排序的,那么咱可以从数组的最右上角开始进行对比,比右上角的值大的向下查找,如果小的话进行左移,如果越界,则说明二维数组中不存在该整数。

public class Search {
	public boolean find(int num, int[][] array) {
		if (array.length == 0 || array[0].length == 0) {
			return false;
		}
		int line = array[0].length - 1;
		int row = 0;
		int tmp = array[row][line];
		while (num != tmp) {
			if (line > 0 && row < array.length - 1) {
				if(num>tmp) {
					row=row+1;
				}else if(num<tmp) {
					line=line-1;
				}
				tmp=array[row][line];
			}else {
				return false;
			}
		}
		return true;
	}
}

2.题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

public class Replace {
	public String replaceSpace(StringBuffer str) {
		StringBuffer res=new StringBuffer();
		int len=str.length()-1;
		for(int i=0;i<=len;i++) {
			if(str.charAt(i)==' ') {
				res.append("20%");
			}else {
				res.append(str.charAt(i));
			}
		}
		return res.toString();
	}
	public static void main(String[] args) {
		StringBuffer s=new StringBuffer("we are happy");
		Replace replace = new Replace();
		System.out.println(replace.replaceSpace(s));
	}
}

3.题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

解题思路
我们可以利用站的先进后出的结构特点,利用栈来实现;
另外一种方法是利用三个指针把链表反转,关键是 r 指针保存断开的节点。

public class ListNode {
	int data;
	ListNode next;

	public ListNode(int data) {
		this.data = data;
	}

}
import java.util.ArrayList;
import java.util.Stack;

public class Reversed {
	public ArrayList<Integer> resverseLineList1(ListNode listNode) {
		if (listNode == null) {
			return new ArrayList<Integer>();
		}
		ListNode head = listNode;
		ListNode nextone = listNode.next;
		while (nextone != null) {
			ListNode tmp = nextone.next;
			nextone.next = head;
			head = nextone;
			nextone = tmp;
		}
		listNode.next = null;
		ArrayList<Integer> arrayList = new ArrayList<Integer>();
		while (head != null) {
			arrayList.add(head.data);
			head = head.next;
		}
		return arrayList;
	}

	/**
	 * 通过栈的方法
	 * 
	 * @param listNode
	 * @return
	 */
	public ArrayList<Integer> resverseLineList2(ListNode listNode) {
		if (listNode == null) {
			return new ArrayList<Integer>();
		}
		ListNode head = listNode;
		ListNode nextone = head.next;
		Stack<Integer> stack = new Stack<>();
		ArrayList<Integer> arrayList = new ArrayList<Integer>();
		while (nextone != null) {
			stack.push(nextone.data);
			nextone = nextone.next;
		}
		while (stack.empty() != false) {
			arrayList.add(stack.pop());
		}
		return arrayList;
	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值