1. 程式人生 > >網易2019筆試題

網易2019筆試題

1.蘋果分堆 

計算累加小組成員數,結合二分查詢,複雜度O( min(n, mlogn) )

package wangyi123;

import java.util.Scanner;

public class groupNum {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while (sc.hasNext()) {
			int n = sc.nextInt();
			int[] arr = new int[n];
			arr[0] = sc.nextInt();
			for (int i = 1; i < n; i++) {
				arr[i] = arr[i - 1] + sc.nextInt();
			}
			int m = sc.nextInt();
			int query = 0;
			int index = 0;
			for (int i = 0; i < m; i++) {
				query = sc.nextInt();
				index = search(arr, query);
				System.out.print(index + " ");
			}

		}
		sc.close();
	}

	public static int search(int a[], int target) {
		int left = 0;
		int right = a.length - 1;
		int mid = 0;
		while (left < right) {
			mid = left + (right - left) / 2;
			if (target >= a[mid]) {
				left = ++mid;
			} else {
				right = mid;
			}
		}
		return left + 1;
	}
}

2.字串理論 

. 

package wangyi123;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class straz {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int m = sc.nextInt();
		int k = sc.nextInt();
		List<String> result = new ArrayList<>();
		dfs(n, m, k, "", result);
		System.out.println(result);
	}

	static boolean flag = false;

	public static void dfs(int n, int m, int k, String s, List<String> result) {
		if (n == 0 && m == 0) {
			result.add(s);
			if (result.size() == k) {
				flag = true;
			}
			return;
		}
		if (flag) {
			return;
		}
		if (n > 0) {
			dfs(n - 1, m, k, s + 'a', result);
		}
		if (m > 0) {
			dfs(n, m - 1, k, s + 'z', result);
		}
	}
}

3.上課瞌睡

package wangyi123;

import java.util.Scanner;

public class sleep {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int k = sc.nextInt();
		int[] a = new int[n];
		int[] t = new int[n];
		for (int i = 0; i < n; i++)
			a[i] = sc.nextInt();
		int now = 0;
		for (int i = 0; i < n; i++) {
			t[i] = sc.nextInt();
			now += t[i] * a[i];
		}
		int res = now;
		for (int i = 0; i < n; i++) {
			if (t[i] == 0) {
				now += a[i];
			}
			if (i + 1 >= k) {
				res = Math.max(res, now);
				if (t[i + 1 - k] == 0) {
					now -= a[i + 1 - k];
				}
			}
		}
		System.out.println(res);

	}

}