首页 > 8.15 题解
头像
lulululud
编辑于 2020-08-17 11:24
+ 关注

8.15 题解

给个小弟的题解吧
第一题,我用的深度搜索比较+剪枝,复杂度n~n^2吧,空间O(n)
具体做法,创建一个数据结构,包括矩阵中元素的值,行列坐标,当前已经访问过的节点列表,
然后两层循环,行列坐标不同并且未访问过,就进行相乘并比较最大值,然后将节点添加进已访问列表,其他情况就跳过
import java.util.*;
public class Solution { public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        ArrayList<Node> list = new ArrayList<>();
        for(int i = 0; i < n; ++i) {
            for(int j = 0; j < m; ++j) {
                list.add(new Node(i, j, sc.nextLong()));
            }
        }  if(n == 1 && n == m) {
            System.out.println(arr[0][0]);
        }
        else {
            long max = 0;
            Node n1, n2;
            for(int i = 0; i < list.size(); ++i) {
                n1 = list.get(i);
                for(Node node : list) {
                    n2 = node;
                    if(n1.row != n2.row && n1.col != n2.col && !n1.visited.contains(n2)) {
                        max = Math.max(max, n1.val * n2.val);
                        n1.visited.add(n2);
                    }
                }
            }
            System.out.println(max);
        }
    }

    static class Node {
        int row, col;
        long val;
        ArrayList<Node> visited;

        public Node(int row, int col, long val) {
            this.row = row;
            this.col = col;
            this.val = val;
            this.visited = new ArrayList<>();
        } }
}
第二题数组,题目的排序方法没想出来
第三题 二进制中的1
import java.util.Scanner;
public class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        long num = sc.nextLong();
        sc.close();
        int ans = 0;

        while(num > 0) {
            if((num & 1) == 1) {
                ++ans;
            }
            num >>= 1;
        }
        System.out.println(ans);
    }
}
第四题,字符串旋转
import java.util.Scanner;
public class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        String str = sc.nextLine();
        sc.close();
        int len = str.length();
        n = n % len;
        System.out.println(str.substring(n) + str.substring(0, n));
    }
}


全部评论

(2) 回帖
加载中...
话题 回帖

相关热帖

近期热帖

历年真题 真题热练榜 24小时
技术(软件)/信息技术类
查看全部

近期精华帖

热门推荐