1、两数之和
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
解答:
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> numMap = new HashMap<>();
for(int i = 0; i < nums.length; i++) {
int num = nums[i];
int needNum = target - num;
if(!numMap.containsKey(needNum)) {
numMap.put(num, i);
continue;
}
return new int[]{numMap.get(needNum), i};
}
return new int[]{};
}
}
2、机器人大冒险
力扣团队买了一个可编程机器人,机器人初始位置在原点(0, 0)。小伙伴事先给机器人输入一串指令command,机器人就会无限循环这条指令的步骤进行移动。指令有两种:
U: 向y轴正方向移动一格
R: 向x轴正方向移动一格。
不幸的是,在 xy 平面上还有一些障碍物,他们的坐标用obstacles表示。机器人一旦碰到障碍物就会被损毁。
给定终点坐标(x, y),返回机器人能否完好地到达终点。如果能,返回true;否则返回false。
示例 1:
输入:command = "URR", obstacles = [], x = 3, y = 2
输出:true
解释:U(0, 1) -> R(1, 1) -> R(2, 1) -> U(2, 2) -> R(3, 2)
解答:
class Solution {
public boolean robot(String command, int[][] obstacles, int x, int y) {
if(command ==null || command.length() < 2 || command.length() > 1000 || !command.contains("U") || !command.contains("R")) {
return false;
}
long max = (long)Math.pow(10, 9);
if(x < 0 || x > max || y < 0 || y > max) {
return false;
}
if(obstacles == null || obstacles.length < 0 || obstacles.length > 1000) {
return false;
}
int validObstacleCount = 0;
for(int i = 0; i <obstacles.length; i++) {
if(obstacles[i][0] <= x && obstacles[i][1] <= y) {
obstacles[validObstacleCount][0] = obstacles[i][0];
obstacles[validObstacleCount][1] = obstacles[i][1];
validObstacleCount++;
}
}
int currentX = 0;
int currentY = 0;
boolean canArriveDest = false;
boolean loop = true;
while(loop) {
for(int i = 0; i < command.length(); i++) {
String cmd = command.charAt(i) + "";
if(cmd.equals("R")) {
currentX++;
} else if(cmd.equals("U")) {
currentY++;
} else {
continue;
}
if(currentX > x || currentY > y) {
loop = false;
break;
}
if(currentX == x && currentY == y) {
canArriveDest = true;
}
for(int j = 0; j < validObstacleCount; j++) {
int[] obstacle = obs