Easy 部分
1. Two Sum
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hash = new HashMap<Integer, Integer>();
int[] res = new int[2];
for(int i = 0;i < nums.length; ++i){
if(hash.containsKey(target-nums[i])){
res[0] = hash.get(target-nums[i]);
res[1] = i;
break;
}
hash.put(nums[i], i);
}
return res;
}
}
26. Remove Duplicates from Sorted Array
class Solution {
public int removeDuplicates(int[] nums) {
int count = 0;
for(int i = 1; i < nums.length; ++i){
if(nums[i] != nums[count]){
nums[++count] = nums[i];
}
}
return count + 1;
}
}
27. Remove Element
class Solution {
public int removeElement(int[] nums, int val) {
int index = 0;
for(int i = 0; i < nums.length; ++i){
if(nums[i] != val){
nums[index++] = nums[i];
}
}
return index;
}
}
由于对顺序没有要求,所以有一种更快的方法
class Solution {
public int removeElement(int[] nums, int val) {
int index = 0;
int len = nums.length;
while(index < len){
if(nums[index] == val){
nums[index] = nums[len - 1];
--len;
}else{
++index;
}
}
return index;
}
}
35. Search Insert Position
普通解法
class Solution {
public int searchInsert(int[] nums, int target) {
int res = -1;
for(int i = 0; i < nums.length; ++i){
if(nums[i] == target || nums[i] > target){
res = i;
break;
}
}
if(res == -1){
res = nums.length;
}
return res;
}
}
基于二分查找的方法
class Solution {
public int searchInsert(int[] nums, int target) {
int low = 0;
int high = nums.length - 1;
while(low <= high){
int mid = (low + high) / 2;
if(nums[mid] == target) return mid;
else if(nums[mid] < target) low = mid + 1;
else high = mid - 1;
}
return low;
}
}
66. Plus One
class Solution {
public int[] plusOne(int[] digits) {
for(int i = digits.length - 1; i >= 0; --i){
if(digits[i] + 1 <= 9){
digits[i]++;
return digits;
}
digits[i] = 0;
}
int[] res = new int[digits.length + 1];
res[0] = 1;
return res;
}
}
网友评论