Title Description:
Given an array nums and a value val, you need to remove in situ all elements whose value is equal to val. The order of the elements may change. Then return the number of elements in nums that differ from val.
Assuming that the number of elements in nums that are not equal to val is k, to pass this question you need to do the following:
Changes the nums array so that the first k elements of nums contain elements that are not equal to val. The rest of the elements of nums and the size of nums do not matter.
Returns k
Thought Analysis:
- Input: array specifying the deletion of val
- Output:The number of elements left after deletion, and the array needs to complete the deletion operation.
- Condition:--
Use double pointer operation, i pointer to find the retained element, j pointer to find the location of the retained element, find the position of the exchange, so that the later find will not repeat the operation.
Error Summary:
- When writing code, try to have a loop variable perform only a single function; too many functions can lead to confusing logic (you should also be careful when writing functions)
- Be careful with the analysis of boundaries and extremes (where the array starts and ends)
Click to view code
//leetcode submit region begin(Prohibit modification and deletion)
func removeElement(nums []int, val int) int {
j := 0
//iFinding elements of retention
for i := 0; i < len(nums); i++ {
//Got it.
if nums[i]!= val{
nums[j] = nums[i]
j++
}
}
return j // j is the length of the new array
}