code刷题

本文深入探讨了Java编程中的各种数据结构和算法应用,包括栈、队列、链表、树和图的实现,以及如何利用这些数据结构解决实际问题。文章通过实例解析了环形链表、回文链表、最小栈等经典问题,同时介绍了动态规划、贪心算法在求解最优解中的应用,如斐波那契数列和零钱兑换问题。此外,还涵盖了字符串处理、二分查找、排序算法以及递归与分治策略。文章旨在提升读者的编程能力和算法思维。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextInt()) { // 注意 while 处理多个 case
            int a = in.nextInt();
            int b = in.nextInt();
            System.out.println(a + b);
        }
    }
}

2021年3月11日

167. 两数之和 II - 输入有序数组

数组numbers.length

字符串s.length()

class Solution {
    public int[] twoSum(int[] numbers, int target) {
        

        int i = 0 ,  j = numbers.length - 1;
        while (i<j){
            int sum = numbers[i]+numbers[j];
            if(sum==target){
                return new int[]{i+1,j+1};
            }else if (sum<target){
                i++;
            }else {
                j--;
            }
        }
        return null;
    }
}

633. 平方数之和

注意 i可以=j

class Solution {
    public boolean judgeSquareSum(int c) {
        if (c<0) return false;
        int i =0 , j = (int)Math.sqrt(c);
        while (i<=j){
            int sum = i*i+j*j;
            if (sum == c){
            return true;
            }else if (sum > c ){
                j--;
            }else {
                i++;
            } 
        }
  
            return false;

        }
   
}
345. 反转字符串中的元音字母

HashSet的创建使用

s.length() 字符串长度需要加()

contains,charAt

return new String (result); 返回合成String

class Solution {
    private static HashSet<Character> yuanyin = new HashSet<>(
        Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')
    );

    public String reverseVowels(String s) {
        if(s==null) return null;
        int i =0 , j = s.length() - 1;
        char[] result =new char[s.length()];
        while (i<= j ){
            char ci = s.charAt(i);
            char cj = s.charAt(j);
            if(!yuanyin.contains(ci)){
                result[i++]=ci;
            }else if (!yuanyin.contains(cj)){
                result[j--]=cj;

            }else{
                result[i++]=cj;
                result[j--]=ci;

            }
        }
       return new String  (result);

    } 
}

2021年3月12日

680. 验证回文字符串 Ⅱ
||a||b短路或ab 全为 false 时,计算结果为 false,否则为 true。
&a&b逻辑与ab 全为 true 时,计算结果为 true,否则为 false

及时写return

class Solution {
    public boolean validPalindrome(String s) {
        for(int i = 0 , j = s.length() -1 ;i < j ; i++,j--){
            if(s.charAt(i)!=s.charAt(j)){ 
                return palindrome(s,i+1,j)||palindrome(s,i,j-1);
            }
        }
        return true;

    }
    public boolean palindrome(String s , int i , int j ){
        while(i<j){
            if(s.charAt(i++)!= s.charAt(j--)){
            return false;
            }

        }
        return true;
    }
}
141. 环形链表
public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head == null){return false;}
        ListNode l1 = head , l2 = head.next;
        while (l1 != null&&l2 != null &&l2.next != null){
            if(l1 == l2) {
                return true;
            }else{
                l1 = l1.next;
                l2 = l2.next.next;
            }
            
            }
            return false;
        }
    }

while (l1 != null ||l2 != null ||l2.next != null)

贪心算法

455. 分发饼干
public int findContentChildren(int[] grid, int[] size) {
    if (grid == null || size == null) return 0;
    Arrays.sort(grid);
    Arrays.sort(size);
    int gi = 0, si = 0;
    while (gi < grid.length && si < size.length) {
        if (grid[gi] <= size[si]) {
            gi++; //满足一个小孩计数
        }
        si++; //无论是否满足都找下一个s
    }
    return gi;
}

class Solution {
    public int maxProfit(int[] prices) {
    int n = prices.length;
    if(n == 0) return 0;
    int left = prices[0];
    int max = 0 ;
    for(int i = 0 ; i<n ; i++){
        if(left>prices[i]){ 
            left = prices[i];
        }else{ max = Math.max(max ,prices[i]-left);
        }
    }
        return max;
        
    }
}
 
 
121. 买卖股票的最佳时机

max = Math.max(max ,prices[i]-left); 前面最大值会被记录

class Solution {
    public int maxProfit(int[] prices) {
    int n = prices.length;
    if(n == 0) return 0;
    int left = prices[0];
    int max = 0 ;
    for(int i = 0 ; i<n ; i++){
        if(left>prices[i]){ 
            left = prices[i];
        }else{ max = Math.max(max ,prices[i]-left);
        }
    }
        return max;
    }
}
122. 买卖股票的最佳时机 II

下标从1开始否则第一段[0,1]会直接加入

error!!
class Solution {
    public int maxProfit(int[] prices) {

        int profit = 0 ;
        for (int i =1 ; i<prices.length-1 ; i++){
            if(prices[i+1]>prices[i]){
                profit+=( prices[i+1]-prices[i]);
            }
        }
        return Profit;
    }
}
class Solution {
    public int maxProfit(int[] prices) {

        int profit = 0 ;
         for (int i = 1; i < prices.length; i++) {
        if (prices[i] > prices[i - 1]) {
            profit += (prices[i] - prices[i - 1]);
        }
    }
        return profit;
    }
}

2021年3月13日

toCharArray() 方法将字符串转换为字符数组

  • public int indexOf(int ch): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
  • public int indexOf(int ch, int fromIndex): 返回从 fromIndex 位置开始查找指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
  • int indexOf(String str): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
  • int indexOf(String str, int fromIndex): 返回从 fromIndex 位置开始查找指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
392. 判断子序列

注意边界控制

i,j从0开始最后一段匹配后要再加一等于n,n为长度

class Solution {
    public boolean isSubsequence(String s, String t) {
        int n = s.length(), m = t.length();
        int i = 0,j =0;
        while (i<n&& j < m){
            if(s.charAt(i)==t.charAt(j)){
                i++;
            }
            j++;
        } 
        return  i==n;
    }
}
53. 最大子序和

https://leetcode-cn.com/problems/maximum-subarray/solution/zui-da-zi-xu-he-by-leetcode-solution/

若当前指针所指元素之前的和小于0,则丢弃当前元素之前的数列

class Solution {
    public int maxSubArray(int[] nums) {
    if(nums==null||nums.length ==0){
        return 0;
    }
    int maxsum =nums[0],  presum = nums[0];
    for(int i =1;i<nums.length;i++){
        presum = presum>0? presum+nums[i]:nums[i];
        maxsum = Math.max(maxsum,presum);
    }return maxsum;
    } 
}

Leetcode 题解 - 二分查找

public int binarySearch(int[] nums, int key) {
 
    int l =0 , r = nums.length -1; 
    while(low <= high){
        int mid = low +( high-low )/2
        if(nums[mid] ==key ){
            return mid;
            
        }else if (nums[mid]>key){
            high = mid-1;
        } else{
            low = mid+1;
            
        }
    }return false;
    
    
}

2021年3月15日

Leetcode 题解 - 链表

合并两个有序链表
 */
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1==null) return l2;
        if(l2==null) return l1;
        if(l1.val < l2.val ){
            l1.next =mergeTwoLists(l1.next, l2);
            return l1 ;

        }else{
            l2.next = mergeTwoLists(l1,l2.next);
            return l2;
        }
    }
}

l1.next =mergeTwoLists(l1.next, l2);

l1第一个数小。则将l1后的链表和l2求mergeTwoLists,并到l1第一个数上

\21. Merge Two Sorted Lists (Easy)

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode begin = null ;
        ListNode mid = head ;
        ListNode last = head.next ;
        while (mid != null){
            mid.next = begin;
            last.next = mid ;
            begin = mid;  //begin = begin.next !!! begin的next 已经为空
            mid = last;
            
            last= last.next;
           
        }
        return mid;

    }
}
206. 反转链表
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode begin = null ;
        ListNode mid = head ;
        
        while (mid != null){
            //last在循环中设定,记录mid的下一个指针
            ListNode last = mid.next;
            last= mid.next ;
            mid.next = begin;
            begin = mid;
            mid = last;
            //可以删除判断,每次last都重新new
            //if (last != null){
                //判断不超出边界
            //last= last.next;
            //}
        }
        return begin;
        //return 的不是mid 
        //mid触碰null,返回begin 放入while (mid != null)

    }
}
class Solution {
   
 public ListNode reverseList(ListNode head) {
    if(head == null||head.next == null  ) return head;
   
    ListNode last = reverseList(head.next);
    head.next.next = head;
    head.next = null;
    return last;
    }
}
83. 删除排序链表中的重复元素
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
       ListNode cur =head;
       while(cur != null&& cur.next != null){
           if(cur.next.val == cur.val ){
               cur.next =cur.next.next; //相同则跳两个
           }else{
               cur = cur.next;//不相同移一个
           }
       }
       return head;
    }
}

Leetcode 题解 - 字符串

242. 有效的字母异位词

题目简单理解为两个数组的字母总体一样

t.toCharArray(); 将s字符串转成数组

Arrays.sort(str2);数组中排序不能直接sort(str2);

Arrays.equals() 两个s不漏

class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.length()!=t.length()){
            return false;
        }
        char[] str1 = s.toCharArray();
        char[] str2 = t.toCharArray();
        Arrays.sort(str1);
        Arrays.sort(str2);
        return Arrays.equals(str1,str2);
    }
}
283. 移动零
 while(index != length-1 ){
            nums[index++] =0; 
        }
        
error!
class Solution {
    public void moveZeroes(int[] nums) {
        int index = 0;
        for(int i = 0 ; i<nums.length ; i++){
            //是i不是index
            if(nums[i]!= 0){
                nums[index++]=nums[i];
            }
        }
        while (index<nums.length){
            nums[index++]=0;
        }

    }
}

2021年3月19日

codetop

1. 两数之和
class Solution {
    public int[] twoSum(int[] nums, int target) {
        if(nums.length == null|| num.length < 2 ){
            return false;
        }
        for(int i = 0 ; i< nums.length ;i++){
            int  x = nums[i];
            for(int j = i+1 ; j < nums.length ;j++ ){
                if(nums[j] ==target - x ){
                    return new int arr[]{i,j};
                }
            }
        }

    }
}

class Solution {
    public int[] twoSum(int[] nums, int target) {
     
        for(int i = 0 ; i< nums.length ;i++){
            int  x = nums[i];
            for(int j = i+1 ; j < nums.length ;j++ ){
                if(nums[j] ==target - x ){
                    return new int []{i,j};
                }
            }
        }
        return new  int[0]; 
        }

    }



2021年3月20日

复习了codetop

141. 环形链表

21. 合并两个有序链表

88. 合并两个有序数组

2021年3月21日

232. 用栈实现队列
class MyQueue {
    //使用双栈来模拟队列,从先进后出到先进先出
	//那么就用一个栈s1来存储,一个栈s2来调换位置就可以
	Stack<Integer> s1;
	Stack<Integer> s2;
	 /** Initialize your data structure here. */
    public MyQueue() {
    	s1=new Stack<Integer>();
    	s2=new Stack<Integer>();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
    	s1.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
    	if (s2.isEmpty()) {
	    	while(!s1.empty()){
	    		s2.push(s1.pop());
	    	}
    	}
    	return s2.pop();
    }
    
    /** Get the front element. */
    public int peek() {
    	if(s2.isEmpty()){
	    	while(!s1.empty()){
	    		s2.push(s1.pop());
	    	}
    	}
    	return s2.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
    	return s1.isEmpty() && s2.isEmpty();
    }
}

2021年3月22日

155. 最小栈

minStack将每次最小的都入栈,出栈一起出

class MinStack {

    /** initialize your data structure here. */
    
        private Stack<Integer> dataStack;
        private Stack<Integer> minStack;
        private int min;

   
    public MinStack(){
        dataStack =new Stack<>();
        minStack =new Stack<>();
        min = Integer.MAX_VALUE;
    }
    
    public void push(int val) {
        dataStack.add(val);
        min = Math.min(min,val);
        minStack.add(min);


    }
    //peek拿最上面一个不出栈
    public void pop() {
        dataStack.pop();
        minStack.pop();
        min = minStack.isEmpty()? Integer.MAX_VALUE:minStack.peek();

    }
    
    public int top() {
        return dataStack.peek();


    }
    
    public int getMin() {
        return minStack.peek();

    }
}



2021年3月23日

public boolean isValid(String s) {
    Stack<Character> stack = new Stack<>();
    for (char c : s.toCharArray()) {
        if (c == '(' || c == '{' || c == '[') {
            stack.push(c);
        } else {
            if (stack.isEmpty()) {
                return false;
            }
            char cStack = stack.pop();
            boolean b1 = c == ')' && cStack != '(';
            boolean b2 = c == ']' && cStack != '[';
            boolean b3 = c == '}' && cStack != '{';
            if (b1 || b2 || b3) {
                return false;
            }
        }
    }
    return stack.isEmpty();
}

2021年3月24日

复习

392. 判断子序列

return i==n;


2021年3月25日

234. 回文链表
class Solution {
    public boolean isPalindrome(ListNode head) {
        Stack <ListNode> stack = new Stack<ListNode>();
        ListNode p = head;
        while(p!=null){
            //p=stack.push();
            // stack.push = p;
            /*
            *
            *
            */
            stack.push(p);
            p = p.next;

        }
        while (head != null){
           // if(head.val != p.val ) return false;
            if(head.val != stack.pop().val) return false;

            head= head.next;
        }return true;

    }
}

—————


2021年3月26日

455. 分发饼干
215. 数组中的第K个最大元素
75. 颜色分类
class Solution {
    public void sortColors(int[] nums) {
        int less = -1;
        int more = nums.length;
        int cur = 0;
        while(cur < more){
            if(nums[cur]<1){
                swap(nums,++less, cur++);
            }else if (nums[cur]>1){
                swap(nums,--more,cur);
            }else{
                cur++;
            }        
        }
    }
    public static void swap(int []arr , int i , int j ){
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp ; 
    }
}

——————


2021年3月27日

70. 爬楼梯
class Solution {
    public int climbStairs(int n) {
        int []f=new int [n+1];
        
        f[0]=1;
        f[1]=1;
        for(int i = 2;i<=n;i++){
            f[i]=f[i-1]+f[i-2];
            
        }
        return f[n];
    }
}

为什么不行f[2] = 2;

509. 斐波那契数
class Solution {
    public int fib(int n) {
         if(n==0) return 0;
         if(n==1) return 1;
         if(n>1){
             return fib(n-1)+fib(n-2);
         }return n;
}
}

剑指 Offer 03. 数组中重复的数字

hashset

img

添加元素:

hashset.add(E e):返回boolean型,如果此 set 中尚未包含指定元素,则添加指定元素;如果此 set 已包含该元素,则该调用不更改 set 并返回 false。

删除元素:

hashset.clear():从此 set 中移除所有元素。

hashset.remove(Object o):如果指定元素存在于此 set 中,则将其移除。

hashset.isEmpty():如果此 set 不包含任何元素,则返回 true。

hashset.contains(Object o):如果此 set 包含指定元素,则返回 true。

hashset.size():返回此 set 中的元素的数量(set 的容量)。

class Solution {
    public int findRepeatNumber(int[] nums) {


        Set <Integer> set = new HashSet<Integer>();
        int repeat =-1;
        for(int num:nums){
            if(!set.add(num)){
            repeat =num;
            break;
            }
        }
          return repeat;

       
    } 
  
}



2021年3月28日

固定数组生成栈
栈:先入后出
这里设置的是固定长度的栈,而不是变长的栈;
除了准备size以外,还应有个index指示,该指示标志的是新来的数放置的位置。

public static class ArrayStack{
	private Integer[] arr;
    private Integer index;
   	public ArrayStack(int initSize) {  
			if (initSize < 0) {
				throw new IllegalArgumentException("The init size is less than 0");
			}
			arr = new Integer[initSize];
			index = 0;
		}
    public Integer peek() {
		if (index == 0) {
			return null;
		}
		return arr[index - 1];
	}

	public void push(int obj) {
		if (index == arr.length) {  //判断满了没
			throw new ArrayIndexOutOfBoundsException("The queue is full");
		}
		arr[index++] = obj;
	}

	public Integer pop() {
		if (index == 0) {
			throw new ArrayIndexOutOfBoundsException("The queue is empty");
		}
		return arr[--index];
	}
}
public void push(int obj){
    if(index == arr.length){
        return false;
        
    }
    arr[index++] = obj;
    
}
public void pop(){
	if(index == 0){
        return false;
    }
    return arr[index--];
    
}
public static void main(int []args){
    private int []arr;
    private int size;
    private int start;
    private int end;
    
    
}

固定数组生成队列
类似于fifo
先入先出
size 约束first和last指针
数组是循环利用的,判断空满只需要判断size的值即可

	public static class ArrayQueue {
		private Integer[] arr;
		private Integer size;
		private Integer first;
		private Integer last;
	public ArrayQueue(int initSize) {
		if (initSize < 0) {
			throw new IllegalArgumentException("The init size is less than 0");
		}
		arr = new Integer[initSize];
		size = 0;    //一开始都指向0
		first = 0;
		last = 0;
	}

	public Integer peek() {  //返回第一个值
		if (size == 0) {
			return null;
		}
		return arr[first];
	}

	public void push(int obj) {   //入栈操作 如果栈满就丢异常
		if (size == arr.length) {
			throw new ArrayIndexOutOfBoundsException("The queue is full");
		}
		size++;  //否则size++
		arr[last] = obj;
		//如果last已经到底,就会回到0位置,循环利用 只要size没超就行
		last = last == arr.length - 1 ? 0 : last + 1;  
	}

	public Integer poll() {
		if (size == 0) {
			throw new ArrayIndexOutOfBoundsException("The queue is empty");
		}
		size--;
		int tmp = first;
		first = first == arr.length - 1 ? 0 : first + 1;
		return arr[tmp];
	}
}
arr = new Integer[initSize];
		size = 0;    //一开始都指向0
		start = 0;
		end = 0;
public void push(int obj){
    if(size==arr.length){
        return false;
        
    }
    size++;
    arr[end] = obj;
    end = end==arr.length -1 ?0:end+1
        //end = arr.length-1 则从头开始    
    
}
public Integer poll() {
    if(size == 0){return false}
    size --;
    int tmp = start;
    start=  start== arr.length -1 ? 0:start +1;
    return arr[tmp];
}

题目二:实现一个特殊的栈,返回最小元素
在实现栈的基本功能的基础上,再实现返 回栈中最小元素的操作。
【要求】
1.pop、push、getMin操作的时间复杂度都是O(1)。
2.设计的栈类型可以使用现成的栈结构。

设计思路:设计两个栈
这里主要是要求getMin的时间复杂度为O(1),所以考虑牺牲额外空间复杂度

一个data栈、一个min栈
data压入一个数,min栈同时压入一个数。如果data数比min栈的栈顶数小,min栈压入data的数;如果min栈顶数小,则再压入一个栈顶数。
如果弹出,则两个栈都同时弹出。
代码如下:

public static class MyStack2 {
    private Stack<Integer> stackData;  
    private Stack<Integer> stackMin;
    public MyStack2() {
        this.stackData = new Stack<Integer>();
        this.stackMin = new Stack<Integer>();
    }

    public void push(int newNum) {  //压栈操作
        if (this.stackMin.isEmpty()) {   //这几个判断都是判断min栈放入什么数
            this.stackMin.push(newNum);
        } else if (newNum < this.getmin()) { //如果data栈的数小于min栈顶,则压入data栈的数
            this.stackMin.push(newNum);
        } else {
            int newMin = this.stackMin.peek(); //min栈顶再压一次
            this.stackMin.push(newMin);
        }
        this.stackData.push(newNum);
    }

    public int pop() {   //同时出栈
        if (this.stackData.isEmpty()) {
            throw new RuntimeException("Your stack is empty.");
        }
        this.stackMin.pop();
        return this.stackData.pop();
    }

    public int getmin() {
        if (this.stackMin.isEmpty()) {
            throw new RuntimeException("Your stack is empty.");
        }
        return this.stackMin.peek();
    }
}

题目3:仅用队列结构实现栈结构与仅用栈结构实现队列结构
一、两个队列实现栈结构:
首先数据先进入队列1,然后除最后一个数外,其余进入队列2
把队列1中的数输出
除队列2中最后一个数外,其余出队列进入队列1
把队列2中的数输出
反复
例如:5、4、3、2、1----5+4321----321+4-----3+21

public static class TwoQueuesStack {
private Queue data; //数据进入的队列
private Queue help; //数据输出的队列

	public TwoQueuesStack() {
		data = new LinkedList<Integer>();
		help = new LinkedList<Integer>();
	}

	public void push(int pushInt) {
		data.add(pushInt);     //所有的输入数据只存放在当前的进入队列中
	}

	public int peek() { //查看栈顶的数
		if (data.isEmpty()) {
			throw new RuntimeException("Stack is empty!");
		}
		while (data.size() != 1) {  //这一步和下面的pop意义一样
			help.add(data.poll());
		}
		int res = data.poll();
		help.add(res);   //区别在这里,返回的结果也会重新放到help中去,不会弹出
		swap();
		return res;
	}

	public int pop() {  //弹出
		if (data.isEmpty()) {
			throw new RuntimeException("Stack is empty!");
		}
		while (data.size() > 1) {  //除了最后一个数,data队列中的所有数输入到help队列里
			help.add(data.poll());
		}
		int res = data.poll(); //直到最后一个数输出
		swap();  //交换两个队列的索引
		return res;
	}

	private void swap() {
		Queue<Integer> tmp = help;
		help = data;
		data = tmp;
	}

}
155. 最小栈
class MinStack {

    /** initialize your data structure here. */
    
        private Stack<Integer> dataStack;
        private Stack<Integer> minStack;
        private int min;

   
    public MinStack(){
        dataStack =new Stack<>();
        minStack =new Stack<>();
        min = Integer.MAX_VALUE;
    }
    
    public void push(int val) {
        dataStack.add(val);
        min = Math.min(min,val);
        minStack.add(min);


    }
    //peek拿最上面一个不出栈
    public void pop() {
        dataStack.pop();
        minStack.pop();
        min = minStack.isEmpty()? Integer.MAX_VALUE:minStack.peek();

    }
    
    public int top() {
        return dataStack.peek();


    }
    
    public int getMin() {
        return minStack.peek();

    }
}


————

__


2021年4月2日

华为上机

https://www.nowcoder.com/practice/cc57022cb4194697ac30bcb566aeb47b?tpId=37&tqId=21329&rp=1&ru=%2Fta%2Fhuawei&qru=%2Fta%2Fhuawei%2Fquestion-ranking&tab=answerKey

字符逆序
//java代码
/**
*字符逆序
*用nextLine(),而不要使用next(),后者只读取有效字符
*/

 
import java.util.Scanner;
 
public class Main{
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        String str = scanner.nextLine();
        String  rts = "";//“”字符串,‘’字符


        for(int i=0;i<str.length();i++){
            rts=str.substring(i,i+1)+rts;
        }
        System.out.println(rts);
    }
}
//substring使用实例

public class Test {
    public static void main(String args[]) {
        String Str = new String("www.runoob.com");
 
        System.out.print("返回值 :" );
        System.out.println(Str.substring(4) );
 
        System.out.print("返回值 :" );
        System.out.println(Str.substring(4, 10) );
    }
}
以上程序执行结果为:

返回值 :runoob.com
返回值 :runoob

https://blog.csdn.net/qq_40126686/article/details/107539490?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522161732973616780264025736%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=161732973616780264025736&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2blogfirst_rank_v2~rank_v29-2-107539490.nonecase&utm_term=%E8%8D%B7%E5%85%B0&spm=1018.2226.3001.4450

//荷兰国旗
public static int[] partition(int []arr , int L, int R , int num){
    int less = L-1;
    int more = R+1;
    int cur = L;
    while(cur<more ){
        if(arr[cur] < num ){
            swap(arr , ++less , cur++);
        }else if ( arr[cur]<num ){
            swap(arr, --more , cur);
        }else{
            cur++;
        }
        
        
    }return new int []{less+1 , more-1};
    
}


2021年4月6日

/*  解题分析:
        设f(m,n) 为m个苹果,n个盘子的放法数目,则先对n作讨论,
        当n>m:必定有n-m个盘子永远空着,去掉它们对摆放苹果方法数目不产生影响。即if(n>m) f(m,n) = f(m,m)  
        当n<=m:不同的放法可以分成两类:
        1、有至少一个盘子空着,即相当于f(m,n) = f(m,n-1); 
        2、所有盘子都有苹果,相当于可以从每个盘子中拿掉一个苹果,不影响不同放法的数目,即f(m,n) = f(m-n,n).
        而总的放苹果的放法数目等于两者的和,即 f(m,n) =f(m,n-1)+f(m-n,n)
    递归出口条件说明:
        当n=1时,所有苹果都必须放在一个盘子里,所以返回1;
        当没有苹果可放时,定义为1种放法;
        递归的两条路,第一条n会逐渐减少,终会到达出口n==1;
        第二条m会逐渐减少,因为n>m时,我们会return f(m,m) 所以终会到达出口m==0.
*/
import java.util.Scanner;
public class Main{
    public static void main(String[] args)
    {
        Scanner sc=new Scanner(System.in);
        while(sc.hasNextInt())
        {
            System.out.println(count(sc.nextInt(),sc.nextInt()));
        }
        sc.close();
    }
    public static int count(int m,int n)
    {
        if(m<0||n<=0)
           return 0;
        //细分到苹果数为一或盘子数为一的情况返回一
        if(m==1||n==1||m==0)
            return 1;
        //将此事件无线细分
        return count(m,n-1)+count(m-n,n);
    }
}

取近似值

https://www.nowcoder.com/practice/3ab09737afb645cc82c35d56a5ce802a?tpId=37&tqId=21230&rp=1&ru=%2Fta%2Fhuawei&qru=%2Fta%2Fhuawei%2Fquestion-ranking&tab=answerKey

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
           double a  = in.nextDouble();
            int b = (int)a;
            if((a-b)>=0.5&&(a-b)<1){
               System.out.println(b+1);
            }else{
                System.out.println(b);
            }
        }
    }
}


2021年4月7日

https://www.nowcoder.com/practice/1221ec77125d4370833fd3ad5ba72395?tpId=37&tqId=21260&rp=1&ru=%2Fta%2Fhuawei&qru=%2Fta%2Fhuawei%2Fquestion-ranking&tab=answerKey

题目描述

有一只兔子,从出生后第3个月起每个月都生一只兔子,小兔子长到第三个月后每个月又生一只兔子,假如兔子都不死,问每个月的兔子总数为多少?

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextInt()) { // 注意 while 处理多个 case
            int n = in.nextInt();
            System.out.println(getnums(n));
        }
        
    }
    
    
    public static int getnums(int n){
        if(n <3){
            return 1;
        }
        return getnums(n-1)+getnums(n-2);
    }
}

找出给定字符串中大写字符(即’A’-‘Z’)的个数。https://www.nowcoder.com/practice/434414efe5ea48e5b06ebf2b35434a9c?tpId=37&tqId=21307&rp=1&ru=%2Fta%2Fhuawei&qru=%2Fta%2Fhuawei%2Fquestion-ranking&tab=answerKey

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (sc.hasNext()) { // 注意 while 处理多个 case
            char[] ch = sc.nextLine().toCharArray();
            int nums = 0; 
            for(int i = 0 ; i <ch.length;i++){
                if(ch[i]>='A'&&ch[i]<='Z'){
                    nums++;
                }
            }System.out.println(nums);
        }
    }
}

while (sc.hasNext())

char[] ch = sc.nextLine().toCharArray();

  • hasNext()方法会判断接下来是否有非空字符.如果有,则返回true,否则返回false
  • hasNextLine() 方法会根据行匹配模式去判断接下来是否有一行(包括空行),如果有,则返回true,否则返回false

toCharArray() 方法将字符串转换为字符数组。

//my error
if(ch>= 'A'&&ch<='Z'){

题目描述

将一个英文语句以单词为单位逆序排放。例如“I am a boy”,逆序排放后为“boy a am I”
所有单词之间用一个空格隔开,语句中除了英文字母外,不再包含其他字符

import java.util.Scanner;
 
/**
 * i am a boy=>boy a am i
 * @author Administrator
 *
 */
public class Main14 {
 
    public static void main(String[] args) {
         
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String str = sc.nextLine();
            int len = str.length();
            String[] s=str.split(" ");
            StringBuilder sb = new StringBuilder();
            for (int i = s.length-1; i >=0; i--) {
                sb.append(s[i]+" ");
            }
             
            System.out.println(sb.substring(0, len));
    }
    }
}
String[]s = str.split(" ");

__


2021年4月10日

https://www.cyc2018.xyz/#%E7%AE%97%E6%B3%95

  • [Java 基础](https://www.cyc2018.xyz/Java/Java 基础.html)
  • [Java 容器](https://www.cyc2018.xyz/Java/Java 容器.html)

明日计划

  • [Java 并发](https://www.cyc2018.xyz/Java/Java 并发.html)
  • [Java 虚拟机](https://www.cyc2018.xyz/Java/Java 虚拟机.html)
198. 打家劫舍
class Solution {
    public int rob(int[] nums) {
        int []dp = new int [1000];
          int n = nums.length;
     	//先对长度限制
        if (n<= 0)
		return 0;
		if (n == 1)
		return nums[0];
        //递归出口
        dp[0] = nums[0];
        dp[1] =nums [1]>nums[0]?nums[1]:nums[0];
        
      /* 这段判断不能放在后面,否则会报错
      	if (n<= 0)
		return 0;
		if (n == 1)
		return nums[0];
       */
        for(int i =2 ; i<n ; i++){//从2开始!
            dp[i] = (nums[i]+dp[i-2])>dp[i-1]?(nums[i]+dp[i-2]):dp[i-1];
        }
        return dp[n-1];
}
}

重叠子问题

斐波那契数列

暴力

11235...
int fib(int n ){
    if(n==1||n==2){
        return 1; 
        
    }
    return fib(n-1)+fib(n-2);
    
}

备忘录:

int fib(int n){
    if(n<1) return 0 ;
    int []memo = new int [n+1];
    for(int i = 0 ; i <n+1; i++){
        memo[i] = 0 ;
    }
    return helper(memo , n);
}
int helper(int [] memo , int n ){
    if(n==1||n==2){
        return 1;
    }
    if(memo[n]!= 0) return memo[n];
    memo[n] =helper(memo, n-1)+helper(memo,n-2);
    return memo[n];
}
        
        
 
 

动态规划 dp

 int fib(int N){
  if (N < 1) return 0;
  int[] memo = new int[N+1];
  for(int i = 0; i < N + 1; i++){
    memo[i] = 0;
  }
  memo[1]=memo[2]=1;
  for(int i = 3; i < N +1;i++){
    memo[i] = memo[i-1] + memo [i-2];
  }
  return memo[N];
}
 

凑零钱问题

给你 k 种面值的硬币,面值分别为 c1, c2 … ck ,每种硬币的数量无限,再给一个总金额 amount ,问你最少需要几枚硬币凑出这个 金额,如果不可能凑出,算法返回 -1

子问题:

​ 凑到amount-1的最少硬币 + 一枚硬币 = 最少硬币数

先确定「状态」,也就是原问题和⼦问题中变化的变量。由于硬币数量⽆

限,所以唯⼀的状态就是⽬标⾦额 amount 。

然后确定 dp 函数的定义:当前的⽬标⾦额是 n ,⾄少需要 dp(n) 个硬

币凑出该⾦额。 //dp=问题(硬币个数)

然后确定「选择」并择优,也就是对于每个状态,可以做出什么选择改变当

前状态。具体到这个问题,⽆论当的⽬标⾦额是多少,选择就是从⾯额列表

coins 中选择⼀个硬币,然后⽬标⾦额就会减少:

int coinChanger( int []coins , int amount){
    int [] memo = new int [amount+1];
    for(int i = 0 ;  i < amount+1; i++){
		memo[i] = -1; 
        
    }
    return dp(coins,amount, memo);
}
int dp(int []coins , int amount , int [ ] memo){
    if(amount ==0 )return 0 ;
    if(amount < 0 )return -1;
    if(memo[amount]!= -1) return memo[amount];
    int res = 9999;
    for(int coin : coins){
        int subProblem = dp(coins,amount-coin,memo);
        if(subProblem  == -1) continue;
        res = Math.min( res,subProblem +1);
    }                      
    memo[amount] = res == amount + 1 ? -1 : res;
    return memo[amount];
}

零钱兑换II–动态规划思路解决相似问题

左神

https://blog.csdn.net/ATFWUS/article/details/104874780?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522161805961716780357289417%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=161805961716780357289417&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2blogfirst_rank_v2~rank_v29-1-104874780.nonecase&utm_term=%E9%9B%B6%E9%92%B1%E5%85%91%E6%8D%A2&spm=1018.2226.3001.4450

给定不同面额的硬币和一个总金额。写出函数来计算可以凑成总金额的硬币组合数,求还钱多少种方法。假设每一种面额的硬币有无限个。 

输入示例:5  1 2  5

输出示例:4

解释:有四种方式可以凑成总金额

5=5   5=2+2+1   5=2+1+1+1   5=1+1+1+1+1
 
class Solution {
    public int change(int amount, int[] coins) {
        if(coins ==null){
            return 0;
        }
        if( amount <=0 ){
            return 1;
        }
        return process1(coins,0,amount);
    }
    public static int process1(int []coins, int index , int amount ){
        int res = 0;
        if(index == coins.length){
            res = amount ==0?1:0;
        }else{
            for(int zhang = 0 ; coins[index]*zhang<= amount ;zhang++){
                res += process1(coins,index+1,amount - coins[index]*zhang);
            }
        }
        return res;
    }
}
//超时
int change(int amount, int* coins, int coinsSize){
    int dp[5001]={0};
    int i,j,k;
    dp[0]=1;
    for(j=0;j<coinsSize;j++)
    {
        for(i=1;i<=amount;i++)
        {
            if(coins[j]>i)continue;
            else{
                dp[i]=dp[i-coins[j]]+dp[i];
            }
        }
    }return dp[amount];
}

2021年4月11日—2021年4月15日 复习完左神初级+高级

2021年4月15日 topcode dfs

200. 岛屿数量
class Solution {
    public int numIslands(char[][] grid) {
        if(grid ==null || grid[0]==null){
            return 0;
        }
        int n = grid.length ;
        int m = grid[0].length;
        int res = 0;
        for ( int i = 0 ; i< n; i++){
            for(int j = 0 ; j < m ;j++){
                if(grid[i][j]=='1'){
                    res++;
                    infect(grid,i,j,n,m);
                }
            }
        }     
        return res;
    }
    public void  infect(char[][]grid ,int i , int j , int n , int m  ){  
         if(i<0||i>=n||j<0||j>=m|| grid[i][j]!='1'){
             return ;
         }
        grid[i][j]='2';
       
       infect(grid,i+1,j,n,m);
       infect(grid,i-1,j,n,m);
       infect(grid,i,j+1,n,m);
       infect(grid,i,j-1,n,m);


    }
}
104. 二叉树的最大深度
class Solution {
    public int maxDepth(TreeNode root) {
         
        if(root==null){
            return 0;
        }
        int l = maxDepth(root.left);
        int r = maxDepth(root.right);
        return (Math.max(l,r)+1);//最开始是1,不是0
    }
    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值