美团 4.23笔试第五题 整数相与
如题。暴力做法,过了45%,超时。我不记得题目中输入数据是否包含负数了。现在想到优化的思路就是建树。测了几个样例是对的。但是现在没法跑后台数据了。还有其它思路不?
import java.util.*; public class test { static class Node{ Node left; Node right; int val; Node(int val) { this.val = val; } } public static void main(String[] args) { Scanner in = new Scanner(System.in); while(in.hasNext()) { int N = in.nextInt(); int[] arr = new int[N]; Node root = new Node(-1); for(int i=0;i<N;i++) { arr[i] = in.nextInt(); createTree(root, arr[i], 0); } boolean[] flag = new boolean[N]; for(int i=0;i<N;i++) { if(find(root, arr[i], 0)) flag[i] = true; } for (int i = 0; i < N; i++) { String s = (flag[i]?1:-1)+" "; System.out.print(s); } } } public static boolean find(Node root, int num, int depth) { if(root==null) { if(depth<33) return false; else if(depth==33) return true; } int val = num%2; int next=num/2; if(val==0) { return find(root.left, next, depth+1)||find(root.right, next, depth+1); } else { return find(root.left, next, depth+1); } } public static void createTree(Node root, int num, int depth) { if(depth>=32) return; int val = num%2; int next = num/2; if(val==0) { if(root.left==null) { Node left = new Node(0); root.left = left; } createTree(root.left, next, depth+1); } else { if(root.right==null) { Node right = new Node(1); root.right = right; } createTree(root.right, next, depth+1); } } }#美团笔试##美团##笔试题目#