首页 > 代码库 > LeetCode--Tags:Array

LeetCode--Tags:Array

Difficulty:Easy

283. Move Zeroes: https://leetcode.com/problems/move-zeroes/

将0移到最后:(i移动遍历,j指向第一个零,遍历到不为零的,则与第一个零调换)

(for if(!=)swap,j++)

技术分享
 1 public class Solution {
 2     public void moveZeroes(int[] nums) {
 3         int j = 0;
 4         for(int i = 0; i < nums.length; i++) {
 5             if(nums[i] != 0) {
 6                 int temp = nums[j];
 7                 nums[j] = nums[i];
 8                 nums[i] = temp;
 9                 j++;
10             }
11         }
12     }
13 }
View Code

 

1. Two Sum:https://leetcode.com/problems/two-sum/

两数和,返回下标数组:(利用HashMap<Key,Value>遍历,其中用到containKey,get(key)--获取value; put<,>;)

(1.HashMap,rst; 2.for() / if(containsKey(tar-num[i]))num[1]get/[0]i,return / put();  3.return)

(有时候题目要求返回数组是基1的,所以是key对于的value都改成i+1了)

技术分享
 1 public class Solution {
 2     public int[] twoSum(int[] nums, int target) {
 3         HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
 4         int[] rst = new int[2];
 5         for (int i = 0; i < nums.length; i++) {
 6             if (map.containsKey(target - nums[i])){
 7                 rst[1] = i;
 8                 rst[0] = map.get(target - nums[i]);
 9                 return rst;
10             }
11             map.put(nums[i],i);
12         }
13         return rst;
14     }
15 }
View Code

 

26. Remove Duplicates from Sorted Array: https://leetcode.com/problems/remove-duplicates-from-sorted-array/

 

LeetCode--Tags:Array