# LeetCode算法代码笔记（26-30）

`给自己的目标：[LeetCode](https://leetcode.com/ "Online Judge Platform") 上每日一题`

## 26. Remove Duplicates from Sorted Array

``````Given input array nums = [1,1,2]
output:length = 2,nums = [1,2]
``````

``````public class Solution {
public int removeDuplicates(int[] nums) {
if (nums.length == 0) {
return 0;
}
int res = 1;
int temp = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] != temp) {
temp = nums[i];
nums[res] = nums[i];
res++;
}
}
return res;
}
}
``````

## 27. Remove Element

``````Given input array nums = [3,2,2,3], val = 3

Your function should return length = 2, with the first two elements of nums being 2.
``````

``````public class Solution {
public int removeElement(int[] nums, int val) {
if (nums.length == 0) {
return 0;
}
int res = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != val) {
nums[res] = nums[i];
res++;
}
}
return res;
}
}
``````

## 28. Implement strStr()

``````public class Solution {
public int strStr(String haystack, String needle) {
return haystack.indexOf(needle);
}
}
``````

## 29. Divide Two Integers

``````63/4 = 15;
63 = 32+16+8+4+3 = 4*2^3+4*2^2+4*2^1+4*2^0+3=(8+4+2+1)*4+3 = 63
``````

``````public class Solution {
public int divide(int dividend, int divisor) {
int sign = 1;
if (dividend < 0) sign = -sign;
if (divisor < 0) sign = -sign;
long temp = Math.abs((long) dividend);
long temp2 = Math.abs((long) divisor);
long c = 1;
while (temp > temp2) {
temp2 = temp2 << 1;
c = c << 1;
}
long res = 0;
while (temp >= Math.abs((long) divisor)) {
while (temp >= temp2) {
temp -= temp2;
res += c;
}
temp2 = temp2 >> 1;
c = c >> 1;
}
if (sign > 0) {
if (res > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
return (int) res;
} else return -(int) res;
}
}
``````

## 30. Substring with Concatenation of All Words `TLE`

``````s: "barfoothefoobarman"
words: ["foo", "bar"]

You should return the indices: [0,9].
``````

``````/**
* 这是 TLE 的代码
*  */
public class Solution {
public List<Integer> findSubstring(String s, String[] words) {
List<Integer> res = new ArrayList<>();
if (s.length() == 0 || words.length == 0) {
return res;
}
Map<String, Integer> map = new HashMap<>();
for (String str : words) {
map.put(str, map.containsKey(str) ? map.get(str) + 1 : 1);
}
int len = words[0].length();
for (int i = 0; i <= s.length() - len * words.length; i++) {
HashMap<String, Integer> tempMap = new HashMap<>(map);
int temp = i;
int count = 0;
String tempStr = s.substring(temp, temp + len);
while (tempMap.containsKey(tempStr) && tempMap.get(tempStr) > 0) {
tempMap.put(tempStr, tempMap.get(tempStr) - 1);
temp = temp + len;
count++;
if (temp + len <= s.length()) {
tempStr = s.substring(temp, temp + len);
} else {
break;
}
}
if (count == words.length) {