Use R studio
Write a function search_insert_position(v, target) which takes a sorted numerical vector v, a numerical target target. If target is present in v, return the index of target. Otherwise, return the index in v of target where it would be if it were inserted in order. The input v is guaranteed to be sorted and to contain unique values (i.e. no duplicates). x <-c(1, 3, 5, 6) search_insert_position (x, 5) ## [1] 3 search_insert_position (x, 2) ## [1] 2 search_insert_position (x, 7) ## [1] 5 Hint: My solution considers various cases separately. I used the functions %in% that tests membership, which to find TRUE indices of a logical vector, and all which tests if all entries of a logical vector are TRUE. Pay particular attention to the final test case above. Testing membership with %in%:
Use R studio
-
- Site Admin
- Posts: 899603
- Joined: Mon Aug 02, 2021 8:13 am