亚马逊java机试题_亚马逊Amazon OA2 -LintCode 九道题-JAVA

627.Longest Palindrome

Given a string which consists of lowercase or uppercase letters, find the length of the

longest palindromes that can be built with those letters.

求一个字符串的最长回文子串

package com.zn.company.amazon;

public class LongestPalindrome {

public static void main(String[] args) {

String str = "abbaccca";

System.out.println(longestPalindrome(str));

}

/**

* 求字符创最长回文子串

*

* @param s

* @return

*/

public static String longestPalindrome(String s) {

StringBuilder longest = new StringBuilder("");

if (s.length() <= 1)

return s;

StringBuilder str = new StringBuilder();

for (int i = 0; i < s.length(); i++) {

str.append("#");

str.append(s.charAt(i));

}

str.append("#");

s = str.toString();

for (int i = 0; i < s.length(); i++) {

expand(str.toString(), longest, i, i);

}

s = longest.toString().replaceAll("#", "");

return s;

}

private static void expand(String s, StringBuilder longest, int i, int j) {

while (i >= 0 && j < s.length()) {

if (s.charAt(i) == s.charAt(j)) {

if (j - i + 1 > longest.length()) {

longest.delete(0, longest.length());

longest.append(s.substring(i, j + 1));

}

i--;

j++;

} else

break;

}

}

}

626.Rectangle Overlap

Given two rectangles, find if the given two rectangles overlap or not.

给出的是两个矩形的左上角和右下角,取两个矩形端点比较靠向中心的(交集),判断这个交集是否为空。

package com.zn.company.amazon;

public class RectangleOverlap {

/**

* 给出的是两个矩形的左上角和右下角,取两个矩形端点比较靠向中心的(交集),判断这个交集是否为空

*

* 判断重叠很麻烦,但判断不重叠很简单的:

*

*/

public boolean doOverlap(Pointer topLeft1, Pointer bottomRight1, Pointer topLeft2, Pointer bottomRight2) {

if (bottomRight1.x > topLeft2.x || bottomRight2.x > topLeft1.x) {

return true;

}

if (bottomRight1.y > topLeft2.y || bottomRight2.y > topLeft1.y) {

return true;

}

return false;

}

}

class Pointer {

public int x;

public int y;

}

604.window sum

Given an array of n integer, and a moving window(size k), move the window at each iteration from the start of the array, find the sum of the element inside the window at each moving.

ExampleFor array [1,2,7,8,5], moving window size k = 3.1 + 2 + 7 = 102 + 7 + 8 = 177 + 8 + 5 = 20return [10,17,20]

一个滑动窗遍历数组,求滑动窗口(大小为k)的和。

package com.zn.company.amazon;

public class WindowSum {

/**

* 一个滑动窗遍历数组,求滑动窗的和。

* @param arr 给定数组

* @param width 窗口大小

* @return

*/

private static int[] windowsum(int[] arr, int width) {

int temp = 0;

int[] result = new int[arr.length - width + 1];

// 计算第一个窗口的sum

for (int i = 0; i < width; i++) {

temp += arr[i];

result[0] = temp;

}

for (int i = width, j = 1; i < arr.length; i++, j++) {

temp += arr[i];

temp -= arr[i - width];

result[j] = temp;

}

return result;

}

}

616.course-schedule-ii

There are a total of n courses you have to take, labeled from 0 to n

- 1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.

There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.

For example:

2, [[1,0]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]

4, [[1,0],[2,0],[3,1],[3,2]]

There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3].

Another correct ordering is[0,2,1,3].

package com.zn.company.amazon;

import java.util.LinkedList;

public class CourseScheduleII {

/*

* @param numCourses: a total of n courses

*

* @param prerequisites: a list of prerequisite pairs

*

* @return: the course order

*

* Given n = 2, prerequisites = [[1,0]] Return [0,1] Given n = 4,

*

* prerequisites = [1,0],[2,0],[3,1],[3,2]] Return [0,1,2,3] or [0,2,1,3]

*/

public int[] findOrder(int numCourses, int[][] prerequisites) {

if (prerequisites == null) {

throw new IllegalArgumentException("illegal prerequisites array");

}

int len = prerequisites.length;

// if there is no prerequisites, return a sequence of courses

if (len == 0) {

int[] res = new int[numCourses];

for (int m = 0; m < numCourses; m++) {

res[m] = m;

}

return res;

}

// records the number of prerequisites each course (0,...,numCourses-1)

// requires

int[] pCounter = new int[numCourses];

for (int i = 0; i < len; i++) {

pCounter[prerequisites[i][0]]++;

}

// stores courses that have no prerequisites

LinkedList queue = new LinkedList();

for (int i = 0; i < numCourses; i++) {

if (pCounter[i] == 0) {

queue.add(i);

}

}

int numNoPre = queue.size();

// initialize result

int[] result = new int[numCourses];

int j = 0;

while (!queue.isEmpty()) {

int c = queue.remove();

result[j++] = c;

for (int i = 0; i < len; i++) {

if (prerequisites[i][1] == c) {

pCounter[prerequisites[i][0]]--;

if (pCounter[prerequisites[i][0]] == 0) {

queue.add(prerequisites[i][0]);

numNoPre++;

}

}

}

}

// return result

if (numNoPre == numCourses) {

return result;

} else {

return new int[0];

}

}

}

612.k closest points找到离目标点最近的k个点

package com.zn.company.amazon;

import java.util.Comparator;

import java.util.PriorityQueue;

/**

* 找到离目标点最近的k个点

* @author ning

*/

public class KCloestPoints {

public Point[] kClosest(Point[] points, Point origin, int k) {

final Point origin_temp;

// write your code here

origin_temp = origin;

PriorityQueue queue = new PriorityQueue<>(k, new Comparator() {

public int compare(Point a, Point b) {

// a点到origin的距离

int disa = (int) (Math.pow((a.x - origin_temp.x), 2) + Math.pow((a.y - origin_temp.y), 2));

// b点到origin的距离

int disb = (int) (Math.pow((b.x - origin_temp.x), 2) + Math.pow((b.y - origin_temp.y), 2));

int diff = disb - disa;

if (diff == 0) {

diff = b.x - a.x;

if (diff == 0) {

diff = b.y - a.y;

}

}

return diff;

}

});

for (int i = 0; i < points.length; i++) {

// 向队列添加元素

queue.offer(points[i]);

if (queue.size() > k) {

queue.poll(); // 移除并返问队列头部的元素

}

}

Point[] result = new Point[k];

for (int i = k - 1; i >= 0; i--) {

result[i] = queue.poll();

}

return result;

}

}

class Point {

int x;

int y;

Point() {

x = 0;

y = 0;

}

Point(int a, int b) {

x = a;

y = b;

}

}

105.Copy List with Random Pointer

带有随机指针的链表,做一次完全的拷贝。

下次尝试O(1)空间复杂度

package com.zn.company.amazon;

import java.util.HashMap;

/**

* 带有随机指针的链表,做一次完全的拷贝。

*

* @author ning

*/

public class CopyListWithRandomPointer {

public RandomListNode copyRandomList(RandomListNode head) {

if (head == null)

return head;

HashMap map = new HashMap();

RandomListNode newHead = new RandomListNode(head.label);

map.put(head, newHead);

RandomListNode pre = newHead;

RandomListNode node = head.next;

while (node != null) {

RandomListNode newNode = new RandomListNode(node.label);

map.put(node, newNode);

pre.next = newNode;

pre = newNode;

node = node.next;

}

node = head;

RandomListNode copyNode = newHead;

while (node != null) {

copyNode.random = map.get(node.random);

copyNode = copyNode.next;

node = node.next;

}

return newHead;

}

}

class RandomListNode {

int label;

RandomListNode next, random;

RandomListNode(int x) {

this.label = x;

}

};628.maximum-subtree

Given a binary tree, find the subtree with maximum sum. Return the root of the subtree.

思路:求二叉树的最大子树和,返回子树根节点,在后续遍历的过程中计树的所有结点值的和。

#include

#include

#include

using namespace std;

struct TreeNode

{

int val;

TreeNode *left;

TreeNode *right;

TreeNode(){}

TreeNode(int val):val(val),left(NULL),right(NULL){}

};

//思路:采用自底向上的计算。先计算左右子树结点的总和,用左右子树的总和加上当前节点值,即可求得当前数的所有结点和

//如果当前总和大于最大值,则更新最大值,同时将最大子树根节点更新为当前根。其实就是后序遍历。

//函数返回值为当前树的所有结点值的和

int MaxSubtree(TreeNode *root , int &maxSum)

{

if(root == NULL)

return 0;

int leftSum = MaxSubtree(root->left , maxSum);

int rightSum = MaxSubtree(root->right , maxSum);

//root->val += leftSum + rightSum;

//maxSum = max(maxSum , root->val);

//return root->val;

int sum = root->val + leftSum + rightSum;

maxSum = max(maxSum , sum);

return sum;

}

int MaxSubtree(TreeNode *root)

{

int result = INT_MIN;

MaxSubtree(root , result);

return result;

}

int main()

{

TreeNode *p1 = new TreeNode(1);

TreeNode *p2 = new TreeNode(2);

TreeNode *p3 = new TreeNode(-3);

TreeNode *p4 = new TreeNode(-4);

TreeNode *p5 = new TreeNode(0);

TreeNode *p6 = new TreeNode(5);

TreeNode *p7 = new TreeNode(-1);

p1->left = p2;

p1->right = p3;

p2->left = p4;

p2->right = p5;

p3->left = p6;

p3->right = p7;

cout<

return 0;

}

注:有任何疑问请在下方留言,谢谢。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值