牛客网——单链表反转

个人主页: 作品专栏: 我变秃了,也变强了 给大家介绍一款程序员必备刷题平台——牛客网

一、单链表反转

将一个给定的单链表反转,例:1-2-3-4-5,反转为5-4-3-2-1

public ListNode reverseList (ListNode head) {
          
   
        ListNode pre = null;
        ListNode next = null;
        while(head != null) {
          
   
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }

二、两数之和

给出一个整型数组 numbers 和一个目标值 target,请在数组中找出两个加起来等于目标值的数的下标,返回的下标按升序排列。 (注:返回的数组下标从1开始算起,保证target一定可以由数组里面2个数字相加得到) 方法1:暴力求解

public int[] twoSum1 (int[] numbers, int target) {
          
   
        //两数之和
        for(int i = 0;i < numbers.length;i++) {
          
   
            for(int j = i + 1;j < numbers.length;j++) {
          
   
                if(numbers[i] + numbers[j] == target) {
          
   
                    return new int[]{
          
   i+1,j+1};
                }
            }
        }
        return new int[2];
    }

方法2:哈希

public int[] twoSum (int[] numbers, int target) {
          
   
        HashMap<Integer,Integer> map = new HashMap<>();
        for (int i = 0; i < numbers.length; i++) {
          
   
            if(map.containsKey(target - numbers[i])) {
          
   
                return new int[]{
          
   map.get(target - numbers[i]),i};
            }
            map.put(numbers[i],i);
        }
        return new int[2];
    }

三、顺时针旋转矩阵

有一个nxn整数矩阵,请编写一个算法,将矩阵顺时针旋转90度。 给定一个nxn的矩阵,和矩阵的阶数n,请返回旋转后的nxn矩阵。

public int[][] rotateMatrix(int[][] mat, int n) {
          
   
        int[][] arr = new int[n][n];
        for (int i = 0; i < mat.length; i++) {
          
   
            for (int j = 0; j < mat[i].length; j++) {
          
   
                arr[j][n-i-1] = mat[i][j];
            }
        }
        return arr;
    }

四、不用加减乘除做加法

写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号

import java.util.*;
public class Solution {
          
   
    public int Add(int num1,int num2) {
          
   
        int ans = 0;
        if(num2 == 0) {
          
   
            return num1;
        }
        while(num2 != 0) {
          
   
            ans = num1 ^ num2;
            num2 = (num1 & num2) << 1;
            num1 = ans;
        }
        return ans;
    }
}
经验分享 程序员 微信小程序 职场和发展