未优化代码
283. 移动零
class Solution {
public void moveZeroes(int[] nums) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length ; j++) {
if (nums[i] == 0 && nums[j] != 0) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
}
}
}
167. 两数之和 II - 输入有序数组
将数组在第一次循环的时候就判断是否是map的key,不是则存储,是就返回,map的key为数组元素,value为相应下标加1(题目要求)
class Solution {
public int[] twoSum(int[] numbers, int target) {
HashMap<Integer, Integer> hashMap = new HashMap();
for (int i = 0; i < numbers.length; i++) {
if (hashMap.containsKey(target - numbers[i])) {
return new int[] { hashMap.get(target - numbers[i]), i + 1};
}
hashMap.put(numbers[i], i + 1);
}
return new int[] {};
}
}