剑指offer (java版本)

题库链接

JZ 1 二维数组中的查找

题目描述
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

示例1:
输入

7,[[1,2,8,9],[2,4,9,12],[4,7,10,13],[6,8,11,15]]

返回值

true
public class Solution {
    public boolean Find(int target, int [][] array) {

        int i=0,j= array[0].length - 1;
        while(i <= array.length-1 && j>=0 ){
           if (array[i][j] == target)
               return true;
           if (array[i][j] > target) j--;
           else if (array[i][j] < target) i++;
        }
        return false;
    }
}

JZ 2 替换空格

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

import java.util.*;


public class Solution {

    public String replaceSpace (String s) {
        // write code here
        int n = s.length();
        char[] array = new char[n*3];
        
        int size=0;
        for (int i=0;i<n;i++){
            char c = s.charAt(i);
            if (c == ' '){
                array[size ++] = '%';
                array[size ++] = '2';
                array[size ++] = '0';
            }
            else
                array[size ++] = c;
        }
        
        String news = new String(array, 0, size);
        return news;
    }
}

JZ 3 从尾到头打印链表

题目描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
示例1:
输入

{67,0,24,58}

返回值

[58,24,0,67]
/**
*    public class ListNode {
*        int val;
*        ListNode next = null;
*
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*
*/
import java.util.*;

public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        Stack<Integer> stack = new Stack<Integer>();
        ListNode tail = listNode;
        
        while(tail!=null){
            stack.push(tail.val);
            tail=tail.next;
        }
        
        ArrayList<Integer> arraylist = new ArrayList<Integer>();
        
        while(!stack.empty())
            arraylist.add(stack.pop());
        return arraylist;
    }
}

JZ50 数组中重复的数字

题目描述

在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中第一个重复的数字。 例如,如果输入长度为7的数组[2,3,1,0,2,5,3],那么对应的输出是第一个重复的数字2。没有重复的数字返回-1。

方法一:set
特点: 无序(没有下标) 集合中的元素不重复

hashset具有去重功能

import java.util.*;


public class Solution {

    public int duplicate (int[] numbers) {
        // write code here
        HashSet<Integer> sites = new HashSet<Integer>();
        int res = -1;
        for(int num:numbers)
            if(!sites.add(num))
            {
                res = num ;
                break;
            }
        
        return res;    
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值