笔试算法练习

1.分糖果
在这里插入图片描述
2.出现一次的数字
在这里插入图片描述
3.重排链表
在这里插入图片描述

public class Solution {
    public void reorderList(ListNode head) {
        if(head==null||head.next==null) return;
             ListNode mid = middleNode(head);
        ListNode l1 = head;
        ListNode l2 = mid.next;
        mid.next = null;
        // 链表逆序
        l2 = reverseList(l2);
        // 合并链表
        mergeList(l1, l2);
    }
        public ListNode middleNode(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while (fast.next!= null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
        }
 
    public ListNode reverseList(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        while (cur != null) {
            ListNode tmp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = tmp;
        }
        return pre;
    }
 
    public void mergeList(ListNode l1, ListNode l2) {
        ListNode l1_tmp;
        ListNode l2_tmp;
        while (l1 != null && l2 != null) {
            l1_tmp = l1.next;
            l2_tmp = l2.next;
 
            l1.next = l2;
            l1 = l1_tmp;
 
            l2.next = l1;
            l2 = l2_tmp;
        }
    }
    
}

4.后序遍历
在这里插入图片描述

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return int整型ArrayList
     */
   public ArrayList<Integer> postorderTraversal (TreeNode root) {
        ArrayList<Integer> res = new ArrayList<>();
        postOrder(root,res);
        return res;
        // write code here
    }
    public void postOrder(TreeNode root,ArrayList<Integer> res){
        if(root==null) return;
        postOrder(root.left,res);
        postOrder(root.right,res);
        res.add(root.val);
    }
}

5.后缀表达式求值
在这里插入图片描述

import java.util.*;


public class Solution {
    /**
     * 
     * @param tokens string字符串一维数组 
     * @return int整型
     */
    public int evalRPN (String[] tokens) {
        // write code here
        Stack<Integer> stack = new Stack();
            for(String token: tokens){
                switch (token){
                    case "+": {
                        stack.push(stack.pop()+stack.pop());
                        break;
                    }
                    case "-": {
                        stack.push(-stack.pop()+stack.pop());
                        break;
                    }
                    case "*": {
                        stack.push(stack.pop()*stack.pop());
                        break;
                    }
                    case "/": {
                        Integer pop = stack.pop();
                        stack.push(stack.pop()/pop);
                        break;
                    }
                    default:{
                        stack.push(Integer.parseInt(token));
                    }
                }
            }
            return stack.pop();
    }
}

6.链表反转

package pratice;
public class reverseList {
    static class ListNode {
        int val;
        ListNode next;
        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
    //    迭代 head 第一个节点
    public static ListNode iterate(ListNode head) {
        ListNode pre = null, next;
        ListNode curr = head;
        while (curr!= null) {
//            保存指针
            next = curr.next;
//            让其指向前一个,head的前一个为null
            curr.next = pre;
//            将当前节点保存在pre
            pre=curr;
//            让当前节点变为下一个
            curr = next;
        }
        return pre;
    }
    //递归
    public static ListNode recursion(ListNode head) {
        //        找到最后一个节点
        if (head == null || head.next == null) {
            return head;
        }
//      最后一个元素
        ListNode node = recursion(head.next);
        head.next.next = head;
        head.next = null;
        return node;
    }
    public static void main(String[] args) {
        ListNode node5 = new ListNode(5, null);
        ListNode node4 = new ListNode(4, node5);
        ListNode node3 = new ListNode(3, node4);
        ListNode node2 = new ListNode(2, node3);
        ListNode node1 = new ListNode(1, node2);
        ListNode pre = iterate(node1);
        System.out.println(pre);
    }
}

7.找到数组的中心下标,即该数左右两边和相等

public class centerIndex {
    public static void main(String[] args) {
        System.out.println(pivotIndex(new int[]{1, 7, 3, 6, 5, 6}));
    }

    private static int pivotIndex(int[] nums) {
        int total = Arrays.stream(nums).sum();
        int left = 0;
        for (int i = 0; i < nums.length; i++) {
            left = left + nums[i];
            if (left == total) {
                return i;
            }
            total = total - nums[i];
        }
        return -1;
    }
}

8.求数组中最大乘积的三个数

public class MaxProduct {
    public static void main(String[] args) {
        System.out.println(sort(new int[]{-3,-2,-1, 1, 2, 3, 4, 5, 6}));
        System.out.println(getMaxMin(new int[]{-3,-2,-1, 1, 2, 3, 4, 5, 6}));
    }

    public static int sort(int[] nums) {
        Arrays.sort(nums);
//        Arrays.asList(nums).stream().forEach(System.out::print);
        int length = nums.length;
        return Math.max(nums[length-1]*nums[length-2]*nums[length-3],nums[0]*nums[1]*nums[length-1]);
    }
//    线性扫描
    public static int getMaxMin(int nums[]){
        int min1=Integer.MAX_VALUE;
        int min2=Integer.MAX_VALUE;
        int max1=Integer.MIN_VALUE;
        int max2=Integer.MIN_VALUE;
        int max3=Integer.MIN_VALUE;
        for (int num : nums) {
          if(num<min1){
              min1=num;
              min2=min1;
          }else if(num<min2){
              min2=num;
          }
          if(num>max1){
             max3=max2;
             max2=max1;
             max1=num;
          }else if(num>max2){
             max3=max2;
             max2=num;
          }else if(num>max3){
              max3=num;
          }
        }
        return Math.max(min1*min2*max1,max1*max2*max3);
    }
}

9.删除数组中重复的数并返回新的数组长度

public class shuzuchongfu {

    public static void main(String[] args) {

        System.out.println(removeDuplicates(new int[]{0, 1, 2, 2, 3, 3, 4}));
    }

    private static int removeDuplicates(int[] nums) {

        if (nums == null || nums.length == 0) return 0;

        int slow = 0;

        for (int fast = 1; fast < nums.length; fast++) {

            if (nums[slow] != nums[fast]) {

                slow++;

                nums[slow] = nums[fast];
            }
        }
        return slow + 1;
    }
}

9.求整数的平方根

public class sqrtX {
    public static void main(String[] args) {
        System.out.println(binarySearch(24));
        System.out.println(newton(24));
    }

    public static int binarySearch(int x) {
        int index = -1, left = 0, right = x;

        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (mid * mid <= x) {
                index = mid;
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return index;
    }

    public static int newton(int x) {
        return (int) sqrt(x, x);
    }

    public static double sqrt(double i, int x) {
        double mid=(i+x/i)/2;
        if(mid==i){
            return i;
        }else{
            return sqrt(mid,x);
        }
    }

10.n以内素数

public class sushu {
    public static int sushuNum(int num) {

        int i, j, k,count=0;
        for (i = 2; i < num; i++) {
            k = (int) Math.sqrt(i);
            for (j = 2; j <= k; j++) {
                if(i%j==0){
                    break;
                }
            }
            if (j>k) {
               count++;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个整数");
        int n = sc.nextInt();
        System.out.println(sushuNum(n));
    }
}

11.数组中两个数相加等于给定的target,求这两个数的下标,两个坐标不能相等(无序)

public class twoNumsAdd {
//   无序数组
    public static void main(String[] args) {
        System.out.println(Arrays.toString(solution(new int[]{1, 2, 3, 4, 5, 6}, 10)));
        System.out.println(Arrays.toString(solution2(new int[]{1, 2, 3, 4, 5, 6}, 10)));
    }

    private static int[] solution2(int[] nums, int target) {
        Map<Integer, Integer> mp = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (mp.containsKey(target - nums[i])) {
                return new int[]{mp.get(target - nums[i]), i};
            } else {
                mp.put(nums[i], i);
            }
        }
        return new int[0];
    }

    private static int[] solution(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }
        return new int[0];
    }

}

12.数组中两个数相加等于给定的target,求这两个数的下标,两个坐标不能相等(有序)

public class twoNumsAdd2 {
    public static void main(String[] args) {
        System.out.println(Arrays.toString(twoPoint(new int[]{0, 1, 2, 3, 4, 5, 6}, 10)));
        System.out.println(Arrays.toString(twoSearch(new int[]{0, 1, 2, 3, 4, 5, 6}, 10)));
    }

    public static int[] twoSearch(int nums[], int target) {
        for (int i = 0; i < nums.length; i++) {
            int low = i, high = nums.length - 1;
            while (low <= high) {
                int mid = low + (high - low) / 2;
                if (nums[mid] == target - nums[low]) {
                    return new int[]{i, mid};
                } else if (nums[mid] > target - nums[low]) {
                    high = mid - 1;
                } else if (nums[mid] < target - nums[low]) {
                    low = mid + 1;
                }
            }
        }
        return new int[0];
    }

    public static int[] twoPoint(int nums[], int target) {
        int low = 0, high = nums.length - 1;
        while (low < high) {
            if (nums[low] + nums[high] == target) {
                return new int[]{low, high};
            } else if (nums[low] + nums[high] < target) {
                low++;
            } else if (nums[low] + nums[high] > target) {
                high--;
            }
        }
        return new int[0];
    }
}

13.斐波那契数列,求某个位置的值

public class feibonaqie {
    public static void main(String[] args) {
        System.out.println(result(10));
        System.out.println(result2(10));
        System.out.println(iterate(10));
    }
//递归
    public static int result(int num) {
        if (num == 0) {
            return 0;
        }
        if (num == 1) {
            return 1;
        }
        return result(num - 1) + result(num - 2);
    }
//
    public static int result2(int num) {
        int[] arr = new int[num + 1];

        return recurse(arr, num);
    }
递归优化
    public static int recurse(int[] arr, int num) {
        if (num == 0) {
            return 0;
        }
        if (num == 1) {
            return 1;
        }
        if (arr[num] != 0) {
            return arr[num];
        }
        arr[num] = recurse(arr, num - 1) + recurse(arr, num - 2);
        return arr[num];
    }
//牛顿递归
    public static int iterate(int num) {
        if (num == 0) {
            return 0;
        }
        if (num == 1) {
            return 1;
        }
        int low = 0, high = 1;
        for (int i = 2; i <= num; i++) {
            int sum = low + high;
            low = high;
            high = sum;
        }
        return high;
    }
}

14.排列硬币 第几行就放几个硬币,总共可放多少行?

public class coin {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个数N");
        int n = sc.nextInt();
        System.out.println(arrangeCoin(n));
        System.out.println(arrangeCoin2(n));
        System.out.println(newton(n));
    }

    public static int arrangeCoin(int n) {
        for (int i = 1; i <= n; i++) {
            n = n - i;
            if (n <= i) {
                return i;
            }
        }
        return 0;
    }

    public static int arrangeCoin2(int n) {
        int low = 0, high = n;
        while (low <= high) {
            //找到中间行
            int mid = low + (high - low) / 2;
//            mid行之前的总数
            int cost = (mid * (mid + 1)) / 2;
            if (cost == n) {
                return mid;
            } else if (cost > n) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }
        return high;
    }

    public static int newton(int n) {
        return (int) sqrt(n, n);
    }

    public static double sqrt(double x, int n) {
        double mid = (x + (2 * n - x) / x) / 2;
        if (mid == x) {
            return x;
        } else {
            return sqrt(mid, n);
        }
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值